"

7 CSS for Style

As noted in the previous chapter, HTML is a language for marking up different parts of the document structure (paragraphs, headings, logical divisions, etc.) and CSS is a language for styling a document. Modern HTML maintains a strict separation of concerns between these two languages. This chapter is all about how CSS works.

CSS Rules

CSS Stands for Cascading StyleSheets. A stylesheet consists of a set of rules concerning how a document is supposed to look.

Here’s a CSS rule that tells the browser to make all paragraph text red:

p {
    color: red;
}

Decoration Connections

As with HTML, most CSS spacing and indenting is there to make it easier for humans to read. You could define the rule above all on one line and the browser would still be able to use it.

p { color: red; }

But you must include the braces { }, the colon and the semicolon or the rule will have a syntax error and may not work the way you expect.

image Do it Yourself

Go to any web page in a Chrome desktop browser (or use this one). Right click and choose “inspect“. Then in the “Styles” pane, you can look at all the CSS rules that are currently applied to the page.

You should also see a + icon. You can click it to add a new CSS rule to the page. Modify it to match the one above. If the page has p elements on it, they will all turn red. This change is temporary, though. When you reload the page it will revert to its original form.

Things to try: Use a different color. Change p to another element type. Does it do what you expected?

You can add the “red paragraphs” rule to a page in two different ways:

  1. You can put it between <style> … </style> tags inside the head element of an HTML document. This is called an internal stylesheet. Here’s what it might look like:
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>Red Text</title>
        <style>
            p {
                color: red;
            }
        </style>
    </head>
    <body>
        <h1>This is not red</h1>
        <p>This is red!</p>
    </body>
    </html>
  2. You could also put it in its own text file (usually with a “.css” extension on its name) and then link to it with a link element inside the head element of an HTML document. The .css file is called an external stylesheet. Web designers often store external stylesheets in a subfolder called css. Here’s what it might look like:
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>Red Text</title>
        <link rel="stylesheet" href="css/my_style.css">
    </head>
    <body>
        <h1>This is not red</h1>
        <p>This is red!</p>
    </body>
    </html>
  3. Note that the link element is an empty element, like img. It does not require a closing tag.

Decoration Connections

Syntax matters a lot to programming languages like Python or Java. Typically a program with a syntax error will not compile or run. In CSS and HTML, the browser does not usually report syntax errors. But it will report other errors, such as a file not found error when an external resource such as an image or a stylesheet fails to load.

To view error reports in Chrome open the developer tools and click the Console tab, as shown below:

The CSS Cascade

The Cascade is the name of the algorithm that decides the order in which CSS rules should be applied. Rules that are applied later can override rules that applied earlier. For example if there are competing rules setting the color of p elements on a web page, the one that is applied later will win. The cascade algorithm is complicated and nuanced, but here are a few general rules:

1. Default CSS Rules have the lowest priority.

Almost any default CSS Rule applied by the browser can be overridden by a CSS rule that you write.

2. Rules that appear lower in a style sheet get applied later. 

If you have two rules setting the color of p elements in one stylesheet, the rule that “wins” will be the one that is defined later in the file.

3. Rules in internal stylesheets get applied after rules in external stylesheets.

This means you can use an external stylesheet to set a base style for all your pages, then tweak the styles for an individual page by adding internal stylesheet rules.

There are lots of other rules to cover more complicated situations, but for now this will be enough.

CSS Rule Syntax

CSS Rules must follow a particular syntax, consisting of a selector followed by a list of CSS “property: value” pairs. The property-value pairs must be inside braces { } and must be separated by semicolons:

selector {
    property: value;
    property: value;
    property: value;
    etc...
}

The simplest selector is a tag name (e.g., p, h1, h2, div, li, ul, img, a, etc.). You can list multiple tag names if you separate them with commas. For example, the rule below will make all h1 and h2 elements white with a dark gray background:

h1, h2 {
    color: white;
    background-color: darkgray;
}

Here’s what the above rule might look like in your file:

Here’s an h2 heading

Here’s a paragraph

You can include as many CSS rules as you like in a stylesheet, one after the other.

Colors

Here’s a list of color names you can use for color and background-color: HTML Color Names.

If you want more fine-grained control, you can also specify the amount of red, green, and blue light you want to mix to make a color. The red, green, and blue values range from 0 to 255.

Here’s an example of how to set paragraphs to orange on a light gray background:

p {
    color: rgb(255, 128, 0);
    background-color: rgb(200, 200, 200);
}

A third way to specify colors is to use hash tag color codes, that specify the red, green, and blue values as a six-digit hexadecimal (base 16) number like this: #FF8000.

Decoration Connections

The colors red, green, and blue are the additive primary colors. Additive color mixing works a little differently from the subtractive color mixing you might be familiar with from mixing paints or inks.

For example, if you turn red, green, and blue up to full power , you get white. If you turn them all the way down to nothing, you get black. Full red and green with no blue gets you yellow. Full red, half green, no blue gets you orange. And any color where the red, green, and blue values are the same will be some shade of gray.

More CSS Properties

CSS is a vast styling language with thousands of properties and values. Here’s a brief rundown of some useful properties, presented as a visual guide to what they do.

  • font-family: serif;
  • font-family: sans-serif;
  • font-family: cursive;
  • font-family: fantasy;
  • font-family: monospace;
  • font-size: 12px;
  • font-size: 16px;
  • font-size: 24px;
  • font-weight: bold;
  • font-weight: normal;
  • font-variant: small-caps;
  • text-decoration: underline;
  • text-decoration: none;
  • text-align: center;
  • text-align: left;
  • text-align: right;
  • text-align: justify;
  • The following can be used with with ol, ul, and li elements.
    • list-style-type: square;
    • list-style-type: circle;
    • list-style-type: disc;
    • list-style-type: decimal;
    • list-style-type: lower-alpha;
    • list-style-type: upper-alpha;
    • list-style-type: none;

If you are looking for something specific, here’s a big, clickable list of every CSS property.

Decoration Connections

Sizes in CSS can be specified using a number of different units. The examples above specify size in pixels (px). note that there should be no spaces between the number and the unit. Use “16px“, not “16 px“. (See the “gotcha” box below).

Positioning Images

Blue-Throated Macaw Figure 1: Floating right.

The topic of positioning images is a big one and we’ll come back to it, but for now you can use the float property to put your images on the left or right and make the text flow around them:

img {
    float: left;
}

or

img {
    float: right;
}

Styling the Whole Page at Once

Everything on the page is inside a body element. To set a style for the whole page at once, you can write a CSS rule for that element. Other elements inside it will inherit the styles from the body element unless you override that inheritance with more CSS rules. You can use the body element to set the font, background color, or starting font size for the whole page.

Here’s an example that sets fonts and colors for the whole page to make it look like an old-school amber monitor from the early 80’s.

body {
    font-family: monospace;
    color: goldenrod;
    background-color: black;
}

You can also set an image as the background of your page by setting the background-image property of the body element:

body {
    background-image: url("images/myimage.png");
}

This will tile the image by default, but you can explore properties such as background-position and background-repeat to override this behavior.

Selecting a Subset of Elements: Class

Sometimes you don’t want to style all the elements of a given type in the same way. For example, the lead paragraph in each section might have need to have a different look than the rest. You can do this with the HTML class attribute.

In the example below, some paragraphs have a class of “lead” while the rest do not:

<h1>First Section</h1>
<p class="lead"> ... </p>
<p> ... </p>

<h1>Second Section</h1>
<p class="lead"> ... </p>
<p> ... </p>

To style just the “lead” paragraphs, use the dot (.) selector in your CSS rule:

p.lead {
    color: darkgray;
    text-indent: 1em;
}

The above rule only applies to p elements with class=”lead”.

Gotcha: Spacing

Remember how we said spacing doesn’t matter? That’s still generally true, except in a few cases.

  • Inside Selectors: The selector “p.lead” means something quite different from “p .lead” where there is a space before the dot. So watch out!
  • With Units: The value “10 px” will not work! The browser will treat it as an error and ignore this part of the rule. Use “10px” instead.

Selecting a Single Element: ID

If you want to apply a set of styles to a single element, use the id attribute to give it a unique identifier. In the example below, div elements are used to enclose different sections of the page, and the id attributes are used to identify the different sections.

<div id="heading">
    <h1>This is the heading</h1>
</div>
<div id="content">
    <p>This is the content</p>
</div>

Then you can use the # selector to apply a rule to a single element with a given id. The rule below makes the background of the heading element blue and makes its text much larger.

#heading {
    background-color: blue;
    font-size:48px;
}

The CSS Cascade Revisited

Earlier we discussed the order of rule application based on where rules were defined  (default styles then external stylesheets then internal stylesheets). Now that we have introduced id and class selectors we also need to talk about the specificity rules of the cascade algorithm.

More specific rules get applied later than less specific rules, so a more specific rule will “win” when there is a conflict with a less specific rule. The calculation of specificity is complicated, but for now it’s enough to know that id selectors are the most specific, followed by class, and then tag selectors.

So if you have a p element with class=”lead”, any p rule will get overridden by any p.lead or .lead rule, no matter where those rules are defined. Similarly if the element has id=”subtitle”, any #subtitle rule will override rules that target only the element’s class or tag.

<exercises chapter=”CSS”>

  1. Go back to the portfolio or online CV page you were creating in the last chapter, and give it some style using an external stylesheet in a new portfolio/css folder (web designers often organize their folders by file type – css, js, images, etc.).
    1. Set a font and a background color for the whole page
    2. Set nicer colors for your headings and links.
    3. Change the list style to make it unique to your page.
    4. Keep going! What else can you do to make the page look better.
  2. There’s an inline HTML element called span that only exists to style individual words or phrases within another element. Choose some types of entity you mention on your portfolio a few times (employers, schools, hobbies, movies, etc.) and surround all entities of those types with <span class=”type”> … </span> tags where “type” is “employer“, “school“, etc. Then create rules using span.type selectors to make those entities stand out in different ways so that a reader can easily identify employers, schools, etc.
  3. Use div elements to create a header and footer section on your page with some content in it (e.g., photo, name, and title for header; contact info and copyright for footer; etc.). Give the div elements unique ids and then use those ids to style the header and footer differently.
  4. Explore CSS with a little online research and see what other interesting properties you can change.

</exercises>