Fundamentals of Web Application Development · DRAFTFreeman

Introduction to CSS

Cascading Style Sheets is the language used to define the presentation of our documents and applications. It provides very fine-grained control over the visual stylings, animations, and even aural properties of the document content.

CSS syntax can be expressive and easy to read. However, some of its underlying concepts often appear unintuitive, which can lead to a frustrating experience of learning layout and styling. Although there are hundreds of CSS properties at a designer’s disposal, in this text we will focus on the fundamentals of authoring style rules, applying rules to elements, and composing layouts with a responsive design mindset, with just a few happy distractions along the way.

Loading Styles

There are three ways to apply styles to a document: external stylesheets, embedded stylesheets, and inline styles. External stylesheets are linked in the head of the document as such:

<head>
  ···
  <link rel="stylesheet" href="/path/to/stylesheet.css" />
  <link rel="stylesheet" href="/path/to/stylesheet2.css" />
</head>

Following our principle of separation of concerns, this is the recommended way to apply styles. In addition to allowing you to use the same stylesheets across different documents (pages), it also allows the browser to cache your styles, which might not often change, separately from the document content which may change more often.

Embedded stylesheets are also located in the head using style elements, as shown here. These are not often used by human authors as it is much easier to author stylesheets in separate files. However, as part of the document (and thus the DOM), styles can be dynamically inserted and manipulated through scripting.

<head>
  <style type="text/css">
    p.highlight {
      color: red;
      border: 1px solid blue;
      font-size: 1.25rem;
    }
  </style>
</head>

Inline styles, as the name implies, appear inline with the document markup as attributes on specific elements, as shown below. This approach is often considered inappropriate as it is difficult to maintain; as we will later see in specificity, inline styles override rules from external stylesheets.

<p style="font-size: 2em; color: red;">Here is some text...</p>