[M1L2]: CSS – Adding Aesthetics

If you have completed the previous lesson, you should have a basic looking HTML page with some information about you and some links, something like this:

 

 

It won’t look very appealing at the moment, because we haven’t provided any styling information.

In the early days of the Web, aesthetic information was often coded directly into HTML.  For backwards-compatibility reasons (that is to say, so that old websites still work), we can still do this, but it is no longer the preferred method to add style information.  Embedding stylistic information into the page creates a few problems.  Fortunately there is a much better way ot do things.

Cascading Style Sheets (CSS)

On the Web, presentational information is now stored separately from the structural ‘markup’ that HTML provides.  We store styling information as a set of rules in a document called a stylesheet.  We write these rules once, then apply them to each page.  The format that this information is stored in is CSS, which stands for Cascading Style Sheets (we will explain the ‘Cascading’ part shortly).

There are many benefits of using CSS rather than embedding style information in the HTML:

  • It makes the HTML easier to read by keeping clutter to a minimum
  • It’s easier to maintain a consistent looka and feel across all pages of your website, especially if it is a big site you can be sure you’ve added the same rules on each page.
  • It’s more efficient; rather than adding a style to every single element individually each time we want to apply a particular style (to make headings red, say), we write a CSS style once and it is automatically applied for every relevant heading.

How CSS Rules Work

CSS rule processing is quite simple.  The stylesheet author uses selectors to target elements within existing HTML. The most basic selectors take their names from the HTML elements they target. For example, the selector p targets <p> elements in HTML.

Each selector within the stylesheet is attached to a set of rules, which consist of properties (e.g. text colour) and values (e.g. red).  Put together, a rule might say something like ‘make all paragraph elements red’. Here is what this rule looks like as CSS:

p {
  color: red;
}

And this line is an example of its effect.

Let’s look at the above CSS in a bit more detail:

CSS p declaration color red

The whole structure is called a rule set (but often “rule” for short). Note also the names of the individual parts:

Selector
The HTML element name at the start of the rule set. It selects the element(s) to be styled (in this case, p elements). To style a different element, just change the selector.
Declaration
A single rule like color: red; specifying which of the element’s properties you want to style.
Properties
Ways in which you can style a given HTML element. (In this case, color is a property of the p elements.) In CSS, you choose which properties you want to affect in your rule.
Property value
To the right of the property after the colon, we have the property value, which chooses one out of many possible appearances for a given property (there are many color values besides red).

Note the other important parts of the syntax:

  • Each rule set (apart from the selector) must be wrapped in curly braces ({}).
  • Within each declaration, you must use a colon (:) to separate the property from its values.
  • Within each rule set, you must use a semicolon (;) to separate each declaration from the next one.

So to modify multiple property values at once, you just need to write them separated by semicolons, like this:

p {
  color: red;
  width: 500px;
  border: 1px solid black;
}

Selecting multiple elements

You can also select multiple types of elements and apply a single rule set to all of them. Include multiple selectors separated by commas. For example:

p, li, h1 {
  color: red;
}

Different types of selectors

There are many different types of selectors. Above, we only looked at element selectors, which select all elements of a given type in the given HTML documents. But we can make more specific selections than that. Here are some of the more common types of selectors:

CSS selector name Example selector What it selects Example HTML selected
Element selector (sometimes called a tag or type selector) p All HTML element(s) of the specified type. <p>
ID selector #my-id The element with the specified ID. On a given HTML page, you’re only allowed one element per ID. <p id="my-id">
Class selector .my-class The element(s) with the specified class (multiple class instances can appear on a page). <p class="my-class"> and <a class="my-class">
Attribute selector img[width] The element(s) on the page with the specified attribute. <img src="myimage.png" width="250"> but not <img src="myimage.png">

There are many more selectors to explore, and you can find a more detailed list in Mozilla’s Selectors guide.

Comments

You can add comments to CSS files using the comment syntax /* */.  Anything between the opening /* and the closing */ is ignored during processing; this includes line breaks. Comments can be inserted anwyhere in your file that you are allowed to use a space.

Authors often use comments to add credits and licensing information at the top of a file, or to insert aides-memoires to remind themselves what a certain rule does.  Here is an example of some comments within a CSS file:

/* 
Author: Chris Sparks
License: Public Domain
*/

p{
  color: red;
}

p.legal{
  font-size: x-small; /* for the small print */
}

Exercises

Let’s try creating some rules in our own stylesheet.  We will use this Glitch example:

Follow these steps:

  • Hover over the Glitch embed above and click ‘remix to edit’
  • Switch to the style.css document
  • Add some rules following the example above. First let’s add a rule to make Level 1 headings appear orange in colour.  Type the following snippet of code:
    h1{
    color: orange;
    }
  • Next, let’s make level two headings italic.  To do this we will set the font-style property to a value of italic:
  • h2{
    font-style: italic;
    }
  • Finally, let’s do something a bit fancy – give our profile photo a rounded frame. To do this we will use CSS’s border-radius feature, which creates rounded corners on an element. The border-radius property takes a numeric value in a variety of different units, but we will use percentage points to set it to 50% of the element’s width. This will make the image appear as if it is in a circular frame:
  • img#profile-picture{
    border-radius: 50%
    }

Glitch doesn’t auto-complete CSS rules, but you will notice that as you type Glitch puts a red circle marker in the left-hand margin of your text, next to the numbered lines.  This feature tells you that your code has errors.  While typing, you can ignore these error messages – Glitch isn’t clever enough to tell the difference between an error that is present because your finished code is incorrect and one that is there because you are in the middle of typing.  If they remain after you’ve finished, check to see what is wrong. Glitch will tell you where it encountered the error, and what it was expecting to see instead. Whenever you encounter this type of error, it is worth carefully reading through your code and comparing it to the rules that it should follow.

Adding a stylesheet to a page

Although we have added some rules for our document, you can see in Glitch’s preview pane that they have not yet taken effect, and our page remains unchanged. This is because we haven’t linked our stylesheet to our page, so they are currently just two unrelated files sitting on the server. We create the link using a <link> element in the HTML document’s head section. The link element is used to create a relationship between the HTML document and another kind of file. It looks like this

<link rel="stylesheet" href="">

The rel attribute tells the browser that this link element points to a stylesheet (links can point to other things too), and the src attribute tells it where that stylesheet can be found. Let’s add the link to our HTML:

  • Select the index.html file in Glitch
  • Find the <title> element, around line 5.  Immediately after the closing </title> tag, press enter to make a new blank line.
  • Type the following: <link rel="stylesheet" href="style.css">

Immediately after you finish typing, the preview pane should update to show the new styles.

A HTML document can have more than one stylesheet attached to it.  This can be useful if we want to use a shared set of styles, or to build our own styles on top of a pre-existing set of rules.  In our Glitch project, we can see a default-styles.css file.  Let’s apply this to our HTML document

  • Select the index.html file in Glitch
  • Find the <title> element, around line 5.  Immediately after the closing </title> tag, press enter to make a new blank line.
  • Type the following: <link rel="stylesheet" href="default-style.css">

The ‘Cascade’

This is a good point to address the ‘cascading’ nature of stylesheets.  We have just seen that multiple stylesheets can be applied to a document – but what if both the stylesheets have a rule for the same element, for example:

— Stylesheet 1 —

p{

color: red;

text-style: italic;

}

— Stylesheet 2 —

p.legal{

font-size: x-small;

color: grey;

}

p{

color: pink;

font-weight: bold;

}

These two rules both apply to the same set of elements, but they are in conflict – the first tells the browser to make the text red and italic, the second to make it pink and bold.  It also tells the browser to make paragraphs with the class=”legal” attribute smaller.   The text can’t be both red and pink, and not all paragraphs have a class so how does the browser decide which to obey?

It works like this:

  • Rules are applied from first to last.  So the first p rule is applied to all paragraphs, making all paragraphs red and italic.  Then the second p rule is also applied, which adds the rule to make them bold.
  • For any conflicting rules, the latest rule takes precedence.  So the color rule from our second file will override the rule from the first; paragraph elements will be pink, not red.
  • More specific rules take precedence over less specific ones.  So any paragraphs with the class="legal" attribute will appear grey, because this rule is more specific, even though there is another less specific rule that appears later.

Styling Your Own Profile

Now let’s add styling information to your own profile page that we created in the previous lesson.

You should have created an account on Glitch.com as part of the introductory exercise.

  • In a new window, log into Glitch and find your project. The easiest way to do this is to click on ‘Your Projects’.
  • Open up the project, and find the HTML you created in the previous lesson, in the index.html file.
  • After the <title></title> element, add the css <link> code from the ‘Adding a Stylesheet to a Page’ section above.  Note that these links will refer to the code in the current project.  You will need to copy across any rules from the style.css that you created above.


That’s the end of our first set of lessons.  I hope you enjoyed making your profile page!

If you want to take things further, I recommend Mozilla’s Excellent ‘Getting Started with the Web’ tutorial, which I used as the starting point for this lesson.

CSS basics by Mozilla Contributors is licensed under the Creative Commons Attribution-ShareAlike 2.5 Generic license.  This page is similarly licensed under CC-BY-SA 2.5.