Intro to CSS

Demo starter files

Now that you know the basics of how to structure a web document using HTML, it's time to get started with styling. This page covers a lot of basics for one lesson, but should make a good reference for you to revisit on your assignments.

Background

Where HTML is meant for the content and logical structure of a web document, CSS (Cascading Style Sheets) handles the visual layout and overall appearance of a page.

The Problem

Before CSS, webmasters used fudgy techniques for spacing and laying out pages. They used blank images to create "spacing", and they used framesets and HTML tables, which were never intended to be used for formatting.

With the introduction of HTML 3.2 in January 1997, new tags like the <font> tag and color attributes made things even worse. Webmasters were now being asked to implement colors and other formatting on web pages, which had to be done tag-by-tag, on every single page. As you can imagine, changing something as simple as a color became a tedious, cumbersome, and expensive task to perform across an entire web site. What a mess!

The Solution

The W3C recognized that this was going to be a problem and had been working on a solution for a few years already, since 1994. In December 1997, HTML version 4 was released as an official standard, with the first "production ready" draft of CSS alongside it. Instead of defining styles and layout on individual tags directly in the HTML, CSS removed all of the visual settings to an entirely separate file.

This solved both problems very effectively. Layout rules are separated from the content, and any number of web pages can reference the same set of rules. Now, when a client requests something like a different font for their heading, the change can be made site-wide in just a single line of code!

CSS has come a long way since then, and new features are being developed and adopted all the time.

An Abstract Medium

Laying out a web page is probably different from almost anything you've encountered before, and it takes some getting used to.

Web sites need to be portable enough to display on myriad device types and display sizes. Unlike print, there is no fixed page size or canvas. You can't double-click on the page to type, or drag objects around to position them on a web page.

The beauty of a truly great web design is not just in the way that it looks, but in how effectively it communicates across the continuum of display sizes and devices.

Flow

So, if a web page doesn't have a fixed size, how do we place things where we want them? We can't really say "2 inches from the top and 3 inches from the left". That certainly doesn't read the same on an iPhone as a computer monitor! There are no truly absolute measurements.

Diagram showing stacked boxes positioned by moving them down, then over
Placing elements in a layout is rarely done using coordinates.

So what's our point of reference? This is partially where the cascade in cascading style sheets comes from.

The only true point of reference we have for elements on a web page are the other elements on the page, relative to each other. If every element demands a certain amount of space for itself, all of the elements can work together to create a flow where everything finds a place.

Diagram showing stacked boxes with arrows pointing away from each one
Elements create a space for themselves following a certain set of rules.

Inheritance

There's one more thing about cascading that's really important to understand. Elements inherit many properties from their parent. This means that when you apply, say, a font to the <body>, everything down to a link, within a list item, within a div, within the body will inherit that font too.

Nested HTML elements with CSS listed alongside each, showing child elements shadowing the top element's setting

This is one of the things that makes CSS so powerful. We don't have to set rules for every element. We set general rules on larger elements, and override those rules as we get to smaller, more specific elements and details.

Nested HTML elements with CSS listed alongside each, showing a child element overriding a setting it would otherwise inherit from its parents

The Box Model

To handle all of this pushing and cascading, style sheets employ a method called the box model.

Every HTML element that renders content on the page is contained in a box. A web page with lots of markup will have a lot of boxes, inside boxes, inside more boxes. This is one of the major reasons why organized, properly nested HTML is so important.

By default, most elements generally fall into one of two categories:

Block elements create a space for themselves. They grow as wide as their container so that all of their "sibling" elements stack either above or below.

Paragraphs are block elements. Each paragraph on the page grows as wide as its container, and other paragraphs sit above or below. Other examples of block elements include <div>, <h1> through <h6>, <ul>, <ol>.

Inline elements are also contained in a box, but they don't clear a space around themselves, so they can sit next to other elements on the same line.

Examples of inline elements include <a>, <em>, <strong>, and <span>.

Of course, we can change this behavior in a number of ways when we need to. Each display mode follows its own set of rules.

Here's what the box model looks like for a block level element:

Illustrated CSS Box Model. Every block element has padding, borders, and margin from the center outward.
  • The element content is the actual text or image or media itself.
  • The padding is the space immediately around this content. Other elements will never share this space.
  • The border is the outline, or stroke, around an element.
  • The margin is the space around the outside of the element. Margins "collapse", so adjacent margins can share the same space.

Let's say you have two elements somewhere in your document, one after the other. The bottom margin of one element is 20 pixels, and the top margin of the element underneath it is 10 pixels.

Two element boxes with shaded margin areas overlapping, the larger of which determining the space between them.

Since margins can overlap, the gap between the two elements will be 20 pixels.

Element 1: "I need at least 20px all around!"
Element 2: "I need at least 10px all around!"

Both elements are satisfied being 20px apart.

Adding CSS to a Document

There are 3 ways to apply styling rules to an HTML document.

  1. Inline, as an attribute, which applies to a single HTML tag
  2. Embedded, or "in-document", which is a style sheet between <style> tags in the <head>
  3. External, using a separate file

We're going to spend most of our time talking about external style sheets, which are the most effective and the most common. It's good to know about the other two methods, but in practice they aren't used as much.

The code to link to an external style sheet is as follows, and it goes inside the <head>:

<head>

  <link rel="stylesheet" href="style/style.css">

</head>
  • The style sheet should go in its own directory, just like images and other types of assets for your websites.
  • I'm going to name my first style sheet style.css, but you can name it whatever you want, as long as it follows normal file naming conventions (lowercase, no spaces, etc.). The file extension must always be .css
  • You can add a <link> tag to as many HTML documents that you want to receive styling from the same style.css style sheet. Just make sure the href points to the right place.

You may see example code online using the <link> tag with an attribute type="text/css". This is no longer required by modern browsers.

Let's add the <link> tag and fill in the HTML for the demo files, then switch over to the style sheet to follow along.

Syntax

The syntax, or grammar, of a CSS document is very simple.

There is no doctype declaration in CSS, nor are there any tags like HTML. You should always define the character set on the very first line though:

@charset "utf-8";

UTF-8 is still what we want to use. We'll talk about other @directives later on, but this is the only one we need to start.

After that, style sheets are basically just a list of rules for the browser to follow when it renders the web page.

h1 {color: red;}

Again, let's break this down:

  • h1 is the selector, or the element in the HTML, that we're targeting.
  • Declarations for that element go between { curly braces }
  • Since we can make more than one declaration at a time, every declaration must end with a ; (semicolon). It's a lot like ending a sentence, telling the browser we're done with this declaration.
  • color is the property we're defining here,
  • and red is the value.

We can make more than one declaration at a time for any given selector:

h1 {color: red; background-color: lightgray;}

CSS ignores the whitespace between declarations though, just like the space between HTML tags, so you should always put declarations in a readable list form, like this:

h1 {
  color: red;
  background-color: lightgray;
}

This will make the <h1> header in our web page appear in red text, on a light gray background.

There are a lot of properties in CSS. The basic ones like color and background-color we'll use a lot, but there are many others that you probably won't memorize right away, if ever. There are tons of resources online for referencing CSS properties and how to use them. Some text editors even have dictionaries built in.

Comments

Comments are just as useful in CSS as they are in HTML. You'll probably use them a lot for toggling rules on and off to see their effect.

In most text editors, the keybinding for toggling a comment is CMD+/ (Command/Control key + Forward Slash). This will comment or uncomment the selected text, or if nothing is highlighted, the entire line that your cursor is currently on.

<!-- HTML comment -->
/* CSS Comment */

Style sheets can sometimes grow very long, so comments are also a really helpful way to create visual sections while scrolling through your document.

Selecting Elements

To get you started, we need to cover some basic selectors for targeting elements.

There are many different ways to target elements in HTML. Some you'll use all the time, and some not so much. Here are some of the basic ones, and we'll talk about some of the more advanced selectors in another lesson.

Remember the syntax is:

selector {
  property: value;
}

Type

Every element of a certain type. This will target all of the <p> tags at once:

HTML:

<p>Paragraph text will be navy.</p>

CSS:

p {
  color: navy;
}

Class

A class is like creating your own tag, and you can add them to almost any element in the <body>. Choose a name that communicates what it does or what it's for, to make it clear and easier to remember. Classes are extremely useful, and you'll use them more than any other kind of selector.

HTML:

<em class="colored">

CSS:

.colored {
  color: navy;
}

You can apply a class to just one element, or as many elements as you like. You can also apply multiple classes to the same element, like this:

<a class="colored minor sidebarlink">

This element has three classes: .colored .minor and .sidebarlink.

Multiple

Multiple selectors can be used at once, separated by commas.

h1, h2, h3 {
  color: navy;
}

They're also sometimes written like this:

h1,
h2,
h3 {
  color: navy;
}

Basic Colors

There are multiple ways to specify a color in CSS. We'll talk about color in a lot more detail in another lesson. For right now the easiest way to specify colors is by choosing from the list of recognized color names.

(Links in the resources below.)

You can either type the name of the color, or use its 6-digit hexadecimal value. If you use the hex value, be sure to precede it with a # sign. Both of these mean the same thing:

.colored { color: olivedrab; }
.colored { color: #6B8E23; }

Olive Drab:

Some text editors include a popup color picker. There are also lots of online color pickers, including a few in the resources below!

Basic Fonts

We'll talk about typography and fonts in more detail very soon, but the simplest way to set a font and guarantee it'll work is to use web safe fonts. Web safe fonts are fonts that we can generally assume are installed on any given computer.

(Links to web safe font lists in the resources below.)

When defining fonts,

  • Font names are case-sensitive
  • Be sure to quote font names that have spaces
  • You should always provide a generic fallback when you specify a font. The most common generic fallbacks are sans-serif and serif.
body {
  font-family: Helvetica, sans-serif;
}
body {
  font-family: "Times New Roman", times, serif;
}

Basic Units

Like colors, CSS supports several units of measurement for specifying sizes, widths, and spacing. The easiest ones to work with for now are probably ems (em), and percentages (%). Pixels (px) are very easy to work with, but you'll find experienced designers and developers use pixel measurements sparingly.

  • The em unit is based on the element's current font size. This unit is extremely useful for creating layouts that scale with the font size.
  • Percentages are every similar to ems. They can be confusing in the beginning, but they are also very important for creating flexible, responsive designs. In most cases they're calculated based on the size of the parent element.
  • Pixels are straightforward and predictable, but that also makes them very "rigid". They generally don't lend themselves well to responsive designs. They are however a better unit of measure to use than points (pt) when specifying exact sizes for the screen.

Whenever you specify values with units in CSS, make sure there's no space between the number and type of units:

Good:

margin: 2em;

Bad:

margin: 2 em;

Centering Content

Content on web pages is centered more often than not. There are older methods of accomplishing this that still work, but they are deprecated and shouldn't be used any more. Those methods include <center> tags and the align="center" attribute.

Centering content is slightly different for each display mode.

Centering Block Elements

Block elements can have margins. To center block elements, set their left and right margins to the special value auto.

.block-centered {
  margin-left: auto;
  margin-right: auto;
}

A margin setting of auto will grow as large as it can. Setting both left and right to auto will center the element, but it might not be immediately obvious. Remember that a block element expands to the full width of its container, so to see the effect of the centering, you'll also have to make its width smaller than its parent.

Centering Inline Elements

Inline content very easy to center. The text-align property in CSS is used to justify inline elements and text.

.inline-centered {
  text-align: center;
}

Let's fill in our style sheet to see some of this new stuff in action.