Here’s a CSS stylesheet tip that I learned today: the negation pseudo-class (meaning it is followed by a colon, like :focus or :visited).  What exactly is it?  Well, its basically the NOT part of an if statement, if you want to think of it that way.  It is extremely useful when you want to apply a style to a class or group of elements, and want to exclude some element(s).

I have a form stylesheet that applies styles to all input elements when focused, but I didn’t want the styles to apply to input elements whose type equals ’submit’ or ‘button’ when focused.  So lets see how it works.

First, I define the style for all input elements:

1
2
3
4
form input, form textarea {
  width:200px;
  padding:1px;
}

To remove these styles (width and padding properties), I can override them later in my stylesheet using:

1
2
3
4
form input[type='submit'], form input[type='button']{
  padding:0px;
  width:auto;
}

This worked great.  I then continued to apply styles to input elements when focused:

1
2
3
4
form input:focus, form textarea:focus {
  color:#000;
  background-color: #EFEFEF;
}

But then, the problem came up with the color property - how do I negate it for the buttons?  I didn’t want to have to specify a color, becuase otherwise it removes the browser/OS styling to the button.  So, I did some research and realized there is negation pseudo-class for CSS (level 3).  Here is how I modified the above style declaration to not include buttons within my form:

1
2
3
4
form input:focus, form textarea:focus, form input:not([type='submit']), form input:not([type='button']) {
  color:#000;
  background-color: #EFEFEF;
}

Now, the styles are only applied to input and textarea elements whose type attibute does NOT equal ’submit’ or ‘button’ - pretty cool.

This entry was posted on Friday, August 1st, 2008 at 1:43 pm.
Categories: Web2.0.

4 Comments, Comment or Ping

  1. Pardon the stupidity on my part,but how are you getting away with using CSS 3?

  2. This is cool stuff. Do you know how recent a browser has to be for these to work?

  3. Dan: haha, good question. I don’t know if I would rely upon this for a production web site, this was more of a proof of concept. However, I think that you could use this in combination with some JS to ensure that the experience is the same across the board - for those browsers that do not support it…

    Ben: Thanks, I thought so… I only tested it in FF3 & IE 7. I think CSS selectors support is limited in IE 6, but is fairy decent in FF2. There’s a good read about CSS3 selectors here:

    http://www.456bereastreet.com/archive/200601/css_3_selectors_explained/

  4. With a bit of jQuery magic you can do this in non-cs3 browsers as well. Just add a class to your css then in your jQuery you can assign the class. Something like this:
    $(”input[type='text'], texarea”)
    .focus(function(){
    $(this).addClass(’foo’);
    })
    .blur(function(){
    $(this).removeClass(’foo’);
    })

Reply to “CSS Negation pseudo-class”