jump to navigation

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

Posted by fofo in CSS.
Tags: , , ,
trackback

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.

Comments»

1. dan - October 5, 2010

yes this confirms my suspicions. thanks for the article. What are the correct order to put things in or is it a question of the last read element in the stylesheet having precedence over an earlier item.

2. JaggiB - September 3, 2011

yes it matters. simple and easy explanation.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: