Front End Engineering, May 2015

CSS 101

CSS Rules

  • A block of CSS code that applies properties to a selection of elements is called a "rule".
  • A rule is made up of a "selector" and one or more property declarations.
  • The selector specifies the set of elements the rule applies to.
  • A property declaration is made up of a property name and one or more property values.
  • Each property declaration ends with a semicolon
  • The list of property declarations goes between curly braces (i.e. { })

Example

div > a // selector
{
  border-color: red;
  // property: value;
  // Also, the whole line is a "rule"
}

::before { } // pseudoelement
:hover { } // pseudoclass

// Muliple selectors for a group of rules

a:hover,
a:active {
   color: chartreuse;
}

Other Notes

  • CSS can be written inside a <style> tag inside the <head>, but it's best practice to put CSS in an external file and link to it using <link rel="stylesheet" href="path/to/css.css">.
  • To select the elements of a certain HTML tag, the selector is just the tag name (e.g. p { })
  • Many CSS properties are inherited. For example, if I set font-size: 62.5%; on the <body> element, then all the elements on the page that don't override font-size will inherit that font size.
  • To find out whether a property is inherited by its children, look up the property on MDN (or Dash.app)

CSS inheritance and specificity

  • CSS can be overriden by declaring a property farther down the "cascade".
  • The highest priority rules are "inline", i.e. defined on the style attribute of a element. This is almost never a good practice to do in your HTML, but is often useful when manipulating styles from JavaScript.
  • Styles in a <style> tag have lower priority than inline styles.
  • Styles in an external CSS file have lower priority than <style> rules
  • You can also override properties by writing a more specific rule. E.g. .my-link is more specific than a, and a.my-link is most specific.
  • The article CSS Specificity: Things You Should Know gives an overview of specificity rules.
  • A class can be added to an element with the class attribute.
  • Use a . between the element name and the class name to select the elements of that tag and class.
  • Use .classname to select all elements of that class.