Override HTML style attribute specificity with CSS

I’ve recently run into a problem when attempting to create a CSS file for print media because some local JavaScript on the page was manipulating the style attributes on the page. Due to specificity issues, it can be very difficult to “correct” the elements to provide proper output. Here’s a new (to me) trick that I just found.

You can override the local style attribute (and any manipulated at runtime with JavaScript) by adding the the [style] modifier to your CSS declaration.

div#someid[style] {
/* your CSS here */

Preventing portions of a webpage from printing

A colleague asked me about my solution for this just the other day, here’s the quick solution.

  1. Add a CSS class attribute to the items.  Assuming they are <div>’s for header and footer, they would look like my example below, but you can add the ‘no-print’ class to anything you don’t want printed.
  2. Add a stylesheet with media=”print” to change the visibility and/or display attributes of that class.
  3. With a little more work, you could add a ‘no-screen’ solution too… this would be advantageous in cases where you may need to mask an account number or SSN.

<link media=”print” href=”print.css” type=”text/css” rel=”stylesheet” />
<div class=”no-print”>This is your header</div>
<div>this is the body</div>
<div class=”no-print”>this is your footer</div>

print.css could then contain:

.no-print { display:none; }