jump to navigation

Order of CSS rules matters!!!!!!!!!! April 1, 2008

Posted by fofo in CSS.
Tags: , , ,
2 comments

I enjoy giving seminars on topics that involve the server side technologies of the web world. but i equally enjoy giving seminars on client side technologies, especially CSS.

one question i often get, and seems to puzzle a lot of people, is the styling of the hyperlink elements in an html document and more specifically why they do not get the underline effect in the hyperlinks, when they hover over. most of them are adamant that they have specified the rules correctly in the external .css. In most cases they have done so correctly. but they do not understand one thing that is of huge importance in CSS.

the order of our rules matters!!!!!!!!!!!!!!!!!!!!

i will try to explain with an example.

when we set certain rules in a .css file for hyperlinks the browser will look for its default built in rule for hyperlinks that says that hyperlinks should be blue and underlined.

so for example, in an external .css file(e.g mystyles.css) we can have the following css code to style our hyperlinks with our own rules

a:link, a:visited{
  font-style:italic;
  font-weight:bold;
  text-decoration:none;
  }

with the above rule,among other things, we take out the underline from all the links.

to achieve the underline effect when we hover over a link, we just form a new rule 

a:hover, a:focus{
  text-decoration:underline;
  }

if we have these rules with that order then everything works fine.

but if you have the rules in the .css file like this

  a:hover, a:focus{
  text-decoration:underline;
  }
 
 a:link, a:visited{
  font-style:italic;
  font-weight:bold;
  text-decoration:none;
  }

then you will not see the underline effect when you hover over hyperlinks. so for all people out there who know how to style the hyperlink elements but do not see the correct output in the browser window, do not panick and  do not blame the browser for “not supporting” that behavior.Just keep in mind, the order of css rules matters.