CSS with style

CSS ("Cascading Style Sheets") is a simple language for adding style information to elements in an HTML document. By "style" I mean any information about how the element should look, instead of what it means. That includes things like:

HTML alone doesn't give you the tools to tell the browser how to do these things. For that, you need CSS.

But first, the HTML boilerplate

Before I talk about CSS in detail, I want to show give you some code to help structure your documents and make them standards-compliant. In the previous chapter, we just started adding HTML elements to our page willy-nilly. This is fine, but it turns out that our lives will be easier if we include our HTML tags inside of this "boilerplate" code. (By "boilerplate" I mean that it's code that you should use as a template.)

Here's the boilerplate:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Your Title Here</title>
    </head>
    <body>
        Your content here
    </body>
</html>

The code in this boilerplate does a couple of things. The DOCTYPE line at the top signals to browsers that your document should be interpreted as HTML5 (the current, most popular standard of HTML). The meta charset line tells browsers that you want the characters in your document to be interpreted as Unicode (specifically, UTF8-encoded Unicode)---if that doesn't make sense, the easy way to explain it is that if you include this line, you can cut-and-paste any character you want into your file (including accented characters), without worrying about the browser displaying garbage instead.

The html, head and body tags are there to ensure that your document has the correct overall structure. Most examples of HTML and CSS you'll find depend on some way in these elements being arranged just right.

So the rule is: whenever you're starting a new web page, cut and paste that code into your text editor. Replace Your Title Here with the title of your page, and replace Your content here with the content of your page.

In the examples below, I'll be showing snippets of HTML without the surrounding boilerplate. I'll assume that you've put the boilerplate into your text editor and are viewing the HTML with the boilerplate in-place.

CSS properties: overview

The way you work with CSS is by assigning "values" to the CSS "properties" of elements. Here's a list of many CSS properties. Every property has its own rules about what "values" are acceptable. Learning CSS is a matter of learning which properties are available, what those properties do, and what values you can assign to them.

A property definition looks like this:

property-name: property-value;

... replacing property-name with the name of the property you want to set, and property-value with the value you want to set for that property. Let's take, for example, the color property, which sets the color of text inside an element. To set the value for this property to red, you would write:

color: red;

Some properties have more sophisticated ways of specifying their value. For example, the border property, which sets the color and size of an element's border, takes multiple values, separated by spaces. Like this:

border: 1px black solid;

We'll go over some of the more useful properties below and give examples of how to set their values below. But don't be afraid to experiment!

Adding styles to individual elements

Of course, it's not enough to just write CSS properties out in the ether. We need something to set the CSS property on! The easiest way to add style to an element is by putting CSS properties directly into the tag's style attribute. For example, take a <p> tag

<p>One of literature's finest paragraphs.</p>

We can change the color of this text by putting a CSS property inside of the element's style attribute:

<p style="color: red;">One of literature's finest paragraphs.</p>

Output:

One of literature's finest paragraphs.

Or, we could set the paragraph's background color:

<p style="background: yellow;">One of literature's finest paragraphs.</p>

Output:

One of literature's finest paragraphs.

You can also set more than one property in the same style attribute, like so:

<p style="color: red; background: yellow;">One of literature's finest
paragraphs.</p>

Output:

One of literature's finest paragraphs.

Let's add one more attribute, to set the size of the font in the paragraph:

<p style="color: red; background: yellow; font-size: 24px;">One of
literature's finest paragraphs.</p>

Output:

One of literature's finest paragraphs.

Types and units of CSS values

As you can see above, the values for CSS properties can look very different from each other, and also sometimes have arcane little letters at the end of them (what's px, for example)? Let's explain a few of them, in particular those that are used in a number of different properties.

Colors

Colors in CSS can be specified in a number of ways; here are some of the most common:

The second and third methods mentioned above deal with colors as a combination of the colors red, green, and blue; the Wikipedia page on the RGB color model has more information. CSS colors are discussed in more detail on the Mozilla Developer Network.

Sizes and lengths

Many CSS properties have values specified with a particular amount that corresponds to some kind of distance or measurement on screen, like font sizes, border widths, shadow offsets, position of an element on the page, etc. Sizes and lengths are commonly expressed in a few different kinds of "units":

Whenever you're specifying a size or length, you need to include one of these units! Attempting to size something with CSS without giving a unit is like asking the question "What is the circumference of this cheesewheel?" and receiving the answer "Six." Six what? Inches? Feet? Miles? Just how big is this cheesewheel.

Useful CSS properties

font-face, font-size, text-align, line-height

color, background, background-image

padding, border, margin

display

width

centering an element on the page: margin: 0 auto;

changing things on the entire page

CSS rules

Of course, writing CSS that applies to only one tag isn't very useful! We especially don't want to be in the business of having to go to each individual tag in a file in order to change styles, if we want to make changes. It would be ideal if there was some way to apply a series of CSS properties not just to an individual tag but to entire categories of tags.

Fortunately, CSS is designed to let us to just this, by writing CSS rules.

A CSS rule looks like this, from a schematic standpoint:

selector { property1: value1; property2: value2; property3: value3; ... }

That is: a "selector" (we'll explain what this is below) followed by a series of properties and values (each of which is followed by a semicolon), enclosed in curly braces. The portion of the rule inside curly braces describes what CSS properties we want to be applied; the "selector" describes what kinds of elements those styles should apply to.

When we write CSS rules, we have to put them in a special place in the HTML file. There's a special tag, called <style>, which needs to be a child of the <head> element. Here's an updated version of the boilerplate code that has this tag ready to go:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <style type="text/css">
            /* put your CSS rules here */
        </style>
        <title>Your Title Here</title>
    </head>
    <body>
        Your content here
    </body>
</html>

CSS Selectors

We mentioned above that the selector determines which elements a CSS rule will apply to. But how do selectors work? What do they look like? They can take a number of forms, which we'll discuss below.

Selecting all elements with a tag name

The simplest kind of selector simply names a tag. The CSS properties in the rule will then be applied to every element that uses this HTML tag. For example, the following rule would make every <em> element render in a slightly larger font than the rest of the page:

em { font-size: 120%; }

Or, to give every <h2> tag a border on the bottom:

h2 { border-bottom: 1px black solid; }

Selecting elements with the same class attribute

You may have noticed that the class attribute of HTML elements appears to be a little bit magical---it shows up everywhere and seems to be associated with the way elements look. The reason for this is that CSS rules can be written to apply to all elements that have their class attribute set to a particular value.

Say, for example, you had an element like this:

<p class="fancypants">Fondue feta cream cheese. Lancashire who moved my
cheese say cheese ricotta fromage monterey jack bavarian bergkase cottage
cheese.</p>

We could write a rule that applies to this element (and not, e.g., any other <p> tags that don't have that class attribute, or have some other class attribute) like so:

.fancypants { text-align: center; font-family: fantasy; line-height: 150%; }

... which would render as:

Fondue feta cream cheese. Lancashire who moved my cheese say cheese ricotta fromage monterey jack bavarian bergkase cottage cheese.

Note that the class fancypants doesn't have any particular built-in meaning---it's just a word that I decided to use for this purpose. You can name your classes whatever you want (with some restrictions---basically, try to just use lowercase letters and hyphens). Just make sure that the class you use in the HTML attribute is the same as the class in the CSS rule.

Part of the power of setting styles this way is that you can potentially have styles that apply to different types of elements (e.g., with different tags). Here's a rule that gives an element a pretty border:

.prettyborder { padding: 5px; border: 3px pink solid; }

Now I can give this class to all different kinds of elements, e.g.

<p>This is <em class="prettyborder">a test</em>. We have a saboteur aboard.
Maybe we better talk out here.</p>
<ul>
    <li class="prettyborder">The observation lounge turned into a swamp.</li>
    <li>Your shields were failing, sir. Not if I weaken first.</li>
    <li>You're going to be an interesting companion.</li>
</ul>

Which would render as:

This is a test. We have a saboteur aboard. Maybe we better talk out here.

Writing a rule that applies to multiple selectors

You may write a rule that you want to apply to some collection of elements that is tricky to write a single selector for. Fortunately, it's possible to specify multiple selectors to apply to a single rule: just put commas between each of the selectors that you want the rule to apply to. For example, here's a rule that applies to <b> tags and <i> tags:

b, i { font-family: monospace; }

Here's that rule in use:

Bold and italic tags. Woo.

You can make a rule that applies to multiple classes as well:

.fancy, .important { color: pink; text-shadow: 3px 3px black; }

If we combine that with the following HTML...

<p><span style="fancy">This is fancy</span> and 
<span style="important">this is important</span>.</p>

... we get:

This is fancy and this is important.

You can, of course, combine rules for classes and rules for tags in the same rule! And you can have more than two selectors, as long as they're all separated by commas:

em, .interesting, .lovely { font-weight: bold; }

This style, applied to this code...

<p><span class="interesting">Interesting</span> and
<span class="lovely">lovely</span> and <em>emphasized</em>.</p>

... produces this:

Interesting and lovely and emphasized.

Pseudo-classes

A pseudo-class allows you to select an element based not on its tag name or its class, but on elements with some characteristic separate from their position in the HTML document. Importantly, there are pseudo-classes that allow you to change the style of <a> tags based on whether or not they've been visited, and to change the style of elements when the mouse hovers over them.

Let's look at the <a> pseudo-classes first. They are :link, :visited and :active. Here's how they work:

You set a style for a pseudo-class by attaching the pseudo-class directly to the end of the selector you want the pseudo-class to apply to. For example, to set the :visited pseudo-class for all <a> tags:

a:visited { color: green; font-size: 110%; }

You could also say that you want the :visited pseudo-class to apply to all members of a particular class like so:

.weird:visited { color: green; }

Use that style with this HTML:

<p><a href="http://aparrish.neocities.org/" class="weird">This link</a> is
weird.</p>

... to get the following result:

This link is weird.

(Note that for privacy reasons, the kinds of CSS attributes that you can apply to :visited links are limited.)

Let's set an :active style for the same class:

.weird:visited { color: green; }
.weird:active { font-size: 150%; }

Use that style with this HTML:

<p><a href="http://aparrish.neocities.org/" class="weird">This link</a> is
weird.</p>

... to get the following result (make sure to hold down your click for a second!):

This link is weird.

The :hover attribute can be applied to any element, not just links. It applies to whatever element is currently under the user's mouse. Let's try it out with this style:

.fun:hover { font-size: 150%; border: 5px pink solid; }

Here's some HTML to test it out with:

<p>Just a normal paragraph.</p>
<p class="fun">This is a FUN paragraph!</p>
<p>Another boring paragraph. Sigh.</p>

Put them together and you get this! (Make sure to move your mouse over the second paragraph.)

Just a normal paragraph.

This is a FUN paragraph!

Another boring paragraph. Sigh.

Other selectors

There are many other ways to write selectors, including sophisticated selectors that allow to write rules that apply to elements based on hierarchical relationships. (We may use some of these later in the class!)

Putting your CSS in a separate file

It's likely that you'll want your CSS rules to apply not just to a single HTML file, but to many different HTML files. Instead of cutting and pasting CSS rules between documents, you might choose instead to put your styles in a separate file. Simply make a new text file and give it a filename ending in .css (say, styles.css). Then, in every HTML file you want to use these styles with, include the following line in the <head> tag:

<link rel="stylesheet" href="styles.css">

(If you used a different name for your file than styles.css, make sure to change the value of the href attribute in the tag above to match.)

Further resources

Again, we've managed only to scratch the surface of what's possible with CSS. I recommend Getting started with CSS from the Mozilla Developer Network if you want more details!

We didn't talk about the "C" in "CSS"---the "cascade," which is a set of rules to determine how CSS rules apply not just to the element you specified in a selector, but to elements that are children of that element. Here's a good, detailed explanation.

Next week, we'll talk a bit more about CSS---specifically, how to position elements on the page.