Friday 22 April 2016

Styling Links with IDs and Classes

As mentioned recently in Project 01: Recreating the Telegraph, I've been struggling to wrap my head around the CSS behind using the <a> tag in conjunction with id and class attributes. I was able to get the functionality to work (somewhat) flawlessly when using the id, but with a class, I had no such luck when trying to apply the same methodology. The thing is, they don't work the same way one bit.


Well, they do kind of work the same way, just a tiny bit backwards. 

Referencing from within an id

When referencing an <a> element within an id, you need to put the id first. For example:

  #navigation a:link, #navigation a:visited {
  color: red
  }

Add a space between the id and the element selector and separate multiple selections with a comma and a space. This will work because the chain for id's is:

  #id > element selector > decoration

The catch is, the id tag must not be placed within an <a> element, it needs to be coded within a parent tag. The code simply doesn't run if the id is placed within the <a> tag because it is then referencing and invalidating itself. 

Referencing from within a class

When referencing an <a> element within a class, you need to put the class name second. For example:

  a:link.navigation, a:visited.navigation {
  color: red
  }

There should be no spaces between the element selector and the class name. Multiple selections should be separated with a comma and a space. My best guess for why the specificity has to be ordered this way is to account for syntax errors if the values were reversed, or had spaces, it would change their meaning entirely. The chain for classes is:

   element selector > .class > decoration

With this approach, the class must be defined within the <a> tag, as to correctly reference itself. 


While perhaps still a bit blurry around the edges, ordering the syntax in the manner does call correctly. For anyone interested in seeing these methods in action, you can simply copy this code here:

No comments:

Post a Comment