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…

[css]
input {
display:block;
width:200px;
border:1px solid #CCC;
background-color:#FFF;
font: normal 12px/12px arial,sans-serif;
padding:0.5em;
}
[/css]

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…

[css]
element[attribute=value]{
css rules
}
[/css]

…and could work in the following manner:

[css]
input[type=submit] {
background-color:#039;
border-color: #000;
cursor:pointer;
color:#FFF;
width:auto;
margin:0.5em;
}
[/css]

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

One thought on “Styling HTML elements in CSS without using classes / IDs

  1. 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

Your email address will not be published. Required fields are marked *