CCS classes vs id

ID's are unique

  • Each element can only have one ID
  • Each page can only have one element with that ID

HTML code will look something like:

  <div id="my-fab-id">

CSS definition will look like

  #my-fab-id {
     text-align: left;
     color: blue;
  }

Classes are not unique

  • You can use the same class on multiple elements
  • You can use multiple classes on the same element

HTML code will look something like:

  <div class="my-fab-class">

CSS definition will look like

.my-fab-class {

     text-align: left;
     color: blue;
  }

CSS Specificity

CSS specificity is quite complicated but the following may help:

  • If two selectors apply to the same element, the more specific one applies
  • The following selectors affect specificity; inline styles, IDs, classes+atributes and elements
  • When selectors have equal specificity, the latest rule wins
  • Rules with more specifc selectors have greater specificity
  • If there's 2 conficting rules, the later rule wins
  • Embedded style sheets have greater specificity than other rules
  • ID selectors have higher specificity than attribute selectors
  • It's good practice to use IDs to increase specificity
  • Class selectors beats element selectors

Bearing this in mind, if you want to add your own custom stylesheet to an existing template, list your stylesheet last, e.g.

 <link rel="stylesheet" href="stylesheets/base.css">
 <link rel="stylesheet" href="stylesheets/skeleton.css">
 <link rel="stylesheet" href="stylesheets/my-fab-styles.css">
 

Using the same CSS definitions for multiple classes/IDs

 
  #content h1, #about h1 {
              font-size: 4em;
              text-shadow: 0 1px white, 2px 2px 0 #DAD7D7;
  }

In this example, the CSS declaration is used for both the “content” and the “about” IDs. Why do this, why not just use “content” or “about”? You probably want all your pages to have the same basic styles. However, you may have a page that for some reason, requires some slight differences. Instead of duplicating all the CSS for both “about” and “content”, just replicate the CSS declarations with the differences and for the rest, add both IDs to the single declaration.

Specifying padding shorthand

I was always forgetting the order of the padding attributes if you want to specify it shorthand. This is the order:

padding-top
padding-right
padding-bottom
padding-left

e.g padding: 2% 0% 2% 10%;

How to remember this? Think T-R-B-L (trouble - which is what I had rememberig the order!)

Recent Changes