What is CSS?

Ever wonder how web pages have a specific look and feel with color, fonts, and layout? These features are part of the Cascading Stylesheet (CSS) language. It provides for the separation of the data in HTML from the styling of the data. Thus, developers can define the look of a webpage separately from the text it contains.

There are three ways to write CSS:

  • Inline CSS: HTML element is styled;
  • Embedded CSS: CSS rules are located in an HTML file; and
  • External CSS: CSS is located in an external file. This makes the CSS code easy to maintain and reusable.

We'll look at each type in the following sections.

CSS syntax

CSS is a rule-based language – you define rules specifying groups of styles that should be applied to particular elements or groups of elements on your web page. For example "I want the main heading on my page to be shown as large red text".

h1 {
    color: red;
    font-size: 5em;
}

The rule opens with a selector . This selects the HTML element that we are going to style. In this case we are styling level one headings (<h1>).

We then have a set of curly braces { }. Inside those will be one or more declarations, which take the form of property and value pairs. Each pair specifies a property of the element(s) we are selecting, then a value that we'd like to give the property.

Before the colon, we have the property, and after the colon, the value. CSS properties have different allowable values, depending on which property is being specified. In our example, we have the color property, which can take various color values. We also have the font-size property. This property can take various size units as a value.

A CSS stylesheet will contain many such rules, written one after the other.

h1 {
    color: red;
    font-size: 5em;
}

p {
    color: black;
}

You will find that you quickly learn some values, whereas others you will need to look up. The individual property pages on MDN give you a quick way to look up properties and their values when you forget, or want to know what else you can use as a value.

Note: You can find links to all the CSS property pages (along with other CSS features) listed on the MDN CSS reference. Alternatively, you should get used to searching for "mdn css-feature-name" in your favorite search engine whenever you need to find out more information about a CSS feature. For example, try searching for "mdn color" and "mdn font-size"!