PHP, Web development, Skiffle…

Styling HTML elements in CSS without using classes / IDs

Something I came across for the first time recently is the practice of using HTML element attributes to apply CSS styles.

The mathematics can be found at http://www.w3.org/TR/CSS2/selector.html#attribute-selectors, but a basic example of where I use this technique is as follows…

starting with a basic form…

Demo Form



To lay the form out cleanly we might apply a few simple CSS styles to the input elements, as follows…

  1. input {
  2. display:block;
  3. width:200px;
  4. border:1px solid #CCC;
  5. background-color:#FFF;
  6. font: normal 12px/12px arial,sans-serif;
  7. padding:0.5em;
  8. }
  9.  

giving us the following…

Demo Form



All well and good, but the submit button is a little kooky because, being an input element, it picks up all the styling rules that we just applied. It’s easy to fix this by applying a few extra CSS styles to the submit button specifically – changing the background color, maybe a rollover effect, stuff like that – and I’ve generally done this by creating a new class specifically for the styling of form buttons .

While this works perfectly well, adding class=”button” to our HTML is completely unnecesary, because we can isolate all submit buttons via CSS attributes. The syntax follows the pattern…

  1. element[attribute=value]{
  2. css rules
  3. }

…and could work in the following manner:

  1.  
  2. input[type=submit] {
  3. background-color:#039;
  4. border-color: #000;
  5. cursor:pointer;
  6. color:#FFF;
  7. width:auto;
  8. margin:0.5em;
  9. }

giving us the following:

Demo Form



This can be used to isolate any HTML element you like – all forms with the method=”post” or all anchor tags with target=”_self” – anything really.

In fact now I type this out it occurs to me that the CSS selectors ‘.’ and ‘#’ (class and ID respectively) are just shorthand for the CSS attribute selectors element[class~=value] and element[id~=value] – more on the ‘~’ operator in another post.

The attribute selectors are a lot more powerful than demonstrated here, and I’ll write a bit about them soon but for the meantime you can read up for yourself at http://www.w3.org/TR/CSS2/selector.html#attribute-selectors.

Safe.
Neil

1 Comment to Styling HTML elements in CSS without using classes / IDs

  1. Tammy's Gravatar Tammy
    January 8, 2010 at 5:23 pm | Permalink

    I am such a geek. I actually read this…I didn’t understand it of course. Now you have to read one of my papers to return the favour.

Leave a Reply

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This widget requires javascript and flash to be installed
copy following tag: