Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS style ignored by <footer>

Until now I used <div>s for header and footer, but as I'm moving to HTML5 I want to replace them with <header> and <footer> tags. The old version had the style definition

#footer a {
  text-decoration: none;
}

to remove the underlining from links. This works as expected. But after changing to the <footer> tag:

footer a {
  text-decoration: none;
}

the style is ignored. What am I doing wrong?

(the full code, including styles, can be found here)

like image 427
Geert Goeteyn Avatar asked Mar 21 '23 18:03

Geert Goeteyn


1 Answers

Specificity.

#footer a is an ID (#footer) and an element (a).

IDs are more specific than classes and classes are more specific than elements.

footer a isn't working because it's two elements, which is very low specificity, and it's being overwritten by a:link which is technically an element and a (psuedo)class, meaning it has higher specificity than two elements.

All you need to do is increase the specificity on the footer a declaration - either give the footer a class or an ID, or do footer a:link, footer a:visited.

Basically it boils down to IDs always override classes always override elements. I believe it's 255 elements = 1 class and 255 classes = 1 ID (but you will never need to be that specific). Inline styles and !important styles are more specific than anything, including IDs. The basic way to calculate specificity is to count the number of IDs, classes, and elements (assuming you don't have to worry about inline styles or !important) in 0,0,0 notation (IDs,classes,elements).

#footer a is 1,0,1.

a:link is 0,1,1.

footer a is 0,0,2.

Those are organized from highest to lowest specificity. To make footer a more specific than a:link you need to add at least 1 class or 1 ID to the declaration, e.g. something like footer#footer a, footer.bottom a, footer a:link, footer a:visited, and so forth (with the class or ID added to the HTML markup accordingly). The last option would not require any HTML markup changed since you are simply overriding the :link and :visited psuedoclasses (which count as real classes in terms of specificity calculations, just as psuedo-elements like :before and :after count as elements).

The simplest of all solutions would be to change the a:link, a:visited style declarations to simply a, which means that declaration will be less specific than the one in the footer and you won't need to alter anything else for it to start working.

Specificity is arguably the single most important concept you need to master in CSS. Here are some good resources to learn more:

  • Specifics on CSS Specificity (CSS Tricks)
  • CSS Specificity (Smashing Mag)
  • CSS Specificity (MDN)
  • Understanding CSS Specificity (Nettuts)
like image 185
Ennui Avatar answered Apr 02 '23 06:04

Ennui