CSS Basics

Let's say we want to use CSS to change the headings on the page: we want the <h2> elements to be centred (instead of the default left-justified) and in an italic font.

The CSS code to do this is below. This is a complete .css file that I have saved as firststyle.css:

h2 {
  text-align: center;
  font-style: italic;
}

In order to make an HTML page actually use this style information, we need to add a tag that indicates what style sheet should be applied to the page. This is done in the <head> (since it is information about the page, not part of the main content) and with the <link> element like this:

To see how this stylesheet actually affects a page, you can see the stylesheet as above applied to a simple HTML page. Here is a screenshot of that page in one web browser before applying the stylesheet, and after:

Simple HTML page with no stylesheet
Simple HTML page with no stylesheet
Simple HTML page with a stylesheet applied
Simple HTML page with a stylesheet applied

As you can see, the stylesheet left most of the default styling unchanged: the level-one heading and paragraphs did not change.

The <h2> elements were selected for change by this CSS: the h2 { … } block (a CSS rule) indicates that we want to change the appearance of every <h2> element.

The “h2” in the CSS is a selector: it indicates which elements we want to modify. In particular, this is a type selector which selects a particular type of element, <h2> in this case. You can select any element for changes this way.

The two lines in the curly braces are CSS declarations that indicate what we want to change. Each is a property, the thing we want to change, and the value that we want to change it to. In this case, we have center-aligned the text, and made the font italic. You can see both of these changes in the figures above, and you should be able to see them on the actual page as well.

There are many properties that you can use in your CSS, and each has values that can be assigned to it. There are also more ways to select content for style changes. We will explore both of these in the following topics.