Introduction

CSS (Cascading Style Sheets) is a language for specifying how documents are presented to users — how they are styled, laid out, etc.

A document is usually a text file structured using a markup language — HTML is the most common markup language, but you may also come across other markup languages such as SVG or XML.

Presenting a document to a user means converting it into a form usable by your audience. Browsers, like Firefox, Chrome, or Edge, are designed to present documents visually, for example, on a computer screen, projector or printer.

CSS can be used for very basic document text styling — for example changing the color and size of headings and links. It can be used to create layout — for example turning a single column of text into a layout with a main content area and a sidebar for related information. It can even be used for effects such as animation.

Applying CSS

The very first thing we need to do is to tell the HTML document that we have some CSS rules we want it to use. There are three different ways to apply CSS to an HTML document that you'll commonly come across, however, for now, we will look at the most usual and useful way of doing so — linking CSS from the head of your document.

Create a file in the same folder as your HTML document and save it as styles.css. The .css extension shows that this is a CSS file.

To link styles.css to index.html add the following line somewhere inside of the HTML document:

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

This <link> element tells the browser that we have a stylesheet, using the rel attribute, and the location of that stylesheet as the value of the href attribute. You can test that the CSS works by adding a rule to styles.css. Using your code editor add the following to your CSS file:

h1{
color: red;
}

Save your HTML and CSS files and reload the page in a web browser. The level one heading at the top of the document should now be red. If that happens, congratulations — you have successfully applied some CSS to an HTML document. If that doesn't happen, carefully check that you've typed everything correctly.

Prerequisites

Before starting this module, you should have:

  • Basic familiarity with using computers, and using the Web passively (i.e. just looking at it, consuming the content.)
  • A basic work environment set up as detailed in Installing basic software, and an understanding of how to create and manage files, as detailed in Dealing with files.
  • Basic familiarity with HTML
  • An understanding of the basics of CSS
Cascade and inheritance

Stylesheets cascade — at a very simple level, this means that the order of CSS rules matter; when two rules apply that have equal specificity the one that comes last in the CSS is the one that will be used.

In the below example, we have two rules that could apply to the h1. The h1 ends up being colored blue — these rules have an identical selector and therefore carry the same specificity, so the last one in the source order wins.

h1 {
color: red;
}

h1 {
color: blue;
}

This is my heading.

Inheritance also needs to be understood in this context — some CSS property values set on parent elements are inherited by their child elements, and some aren't.

For example, if you set a color and font-family on an element, every element inside it will also be styled with that color and font, unless you've applied different color and font values directly to them.

Some properties do not inherit — for example, if you set a width of 50% on an element, all of its descendants do not get a width of 50% of their parent's width. If this was the case, CSS would be very frustrating to use!

Types of selectors

In CSS, selectors are used to target the HTML elements on our web pages that we want to style. There are a wide variety of CSS selectors available, allowing for fine-grained precision when selecting elements to style.

A CSS selector is the first part of a CSS Rule. It is a pattern of elements and other terms that tell the browser which HTML elements should be selected to have the CSS property values inside the rule applied to them. The element or elements which are selected by the selector are referred to as the subject of the selector.

This group includes selectors that target an HTML element such as an <h1>.

h1 { }

It also includes selectors which target a class:

.box { }

or, an ID:

#unique { }


Attribute selectors give you different ways to select elements based on the presence of a certain attribute on an element:

a[title] { }

Or even make a selection based on the presence of an attribute with a particular value:

a[href="https://example.com"] { }


Pseudo-classes style certain states of an element. The :hover pseudo-class for example selects an element only when it is being hovered over by the mouse pointer:

a:hover { }

It also includes pseudo-elements, which select a certain part of an element rather than the element itself. For example, ::first-line always selects the first line of text inside an element (a <p> in the below case):

p::first-line { }

Values and units

In CSS specifications and on the property pages here on MDN you will be able to spot value types as they will be surrounded by angle brackets, such as color or length. When you see the value type color as valid for a particular property, that means you can use any valid color as a value for that property, as listed on the color reference page.

In the following example, we have set the color of our heading using a keyword, and the background using the rgb() function:

h1 {
color: black;
background-color: rgb(197,93,161);
}

The numeric type you will come across most frequently is <length>. For example 10px (pixels) or 30em. There are two types of lengths used in CSS — relative and absolute. It's important to know the difference in order to understand how big things will become.


Absolute length units are not relative to anything else, and are generally considered to always be the same size.

Most of these units are more useful when used for print, rather than screen output. For example, we don't typically use cm (centimeters) on screen. The only value that you will commonly use is px (pixels).


Relative length units are relative to something else, perhaps the size of the parent element's font, or the size of the viewport. The benefit of using relative units is that with some careful planning you can make it so the size of text or other element scales relative to everything else on the page.

em and rem are the two relative lengths you are likely to encounter most frequently when sizing anything from boxes to text. It's worth understanding how these work, and the differences between them, especially when you start getting on to more complex subjects like styling text or CSS layout. The below example provides a demonstration.

To start with, we set 16px as the font size on the <html> element.

To recap, the em unit means "my parent element's font-size" in the case of typography. The <li> elements inside the <ul> with a class of ems take their sizing from their parent. So each successive level of nesting gets progressively larger, as each has its font size set to 1.3em — 1.3 times its parent's font size.

To recap, the rem unit means "The root element's font-size". (rem stands for "root em".) The <li> elements inside the <ul> with a class of rems take their sizing from the root element (<html>). This means that each successive level of nesting does not keep getting larger.

However, if you change the <html> font-size in the CSS you will see that everything else changes relative to it — both rem- and em-sized text.

The box model

Everything in CSS has a box around it, and understanding these boxes is key to being able to create layouts with CSS, or to align items with other items.

In CSS we broadly have two types of boxes — block boxes and inline boxes. These characteristics refer to how the box behaves in terms of page flow, and in relation to other boxes on the page:

If a box is defined as a block, it will behave in the following ways:

  • The box will break onto a new line.
  • The box will extend in the inline direction to fill the space available in its container. In most cases this means that the box will become as wide as its container, filling up 100% of the space available.
  • The width and height properties are respected.
  • Padding, margin and border will cause other elements to be pushed away from the box

Unless we decide to change the display type to inline, elements such as headings (e.g. <h1>) and <p> all use block as their outer display type by default.


If a box has an outer display type of inline, then:

  • The box will not break onto a new line.
  • The width and height properties will not apply.
  • Vertical padding, margins, and borders will apply but will not cause other inline boxes to move away from the box.
  • Horizontal padding, margins, and borders will apply and will cause other inline boxes to move away from the box.

The <a> element, used for links, <span>, <em> and <strong> are all examples of elements that will display inline by default.

The type of box applied to an element is defined by display property values such as block and inline, and relates to the outer value of display.

The full CSS box model applies to block boxes, inline boxes only use some of the behavior defined in the box model. The model defines how the different parts of a box — margin, border, padding, and content — work together to create a box that you can see on the page.


Making up a block box in CSS we have the:

  • Content box: The area where your content is displayed, which can be sized using properties like width and height.
  • Padding box: The padding sits around the content as white space; its size can be controlled using padding and related properties.
  • Border box: The border box wraps the content and any padding. Its size and style can be controlled using border and related properties.
  • Margin box: The margin is the outermost layer, wrapping the content, padding and border as whitespace between this box and other elements. Its size can be controlled using margin and related properties.

Backgrounds and borders

The background-color property defines the background color on any element in CSS. The property accepts any valid <color>. A background-color extends underneath the content and padding box of the element.

In the example below, we have used various color values to add a background color to the box, a heading, and a <span> element.


CSS:

.box {
background-color: #567895;
}

h2 {
background-color: black;
color: white;
}

span {
background-color: rgba(255,255,255,.5);
}


HTML:

<div class="box">
<h2>Background Colors</h2>
<p>Try changing the background <span>colors</span>.</p>
</div>

<div class="box">
<h2>Background Colors</h2>
<p>Try changing the background <span>colors</span>.</p>
</div>


The background-image property enables the display of an image in the background of an element.

The background-repeat property is used to control the tiling behavior of images. The available values are:

  • no-repeat — stop the background from repeating altogether.
  • repeat-x — repeat horizontally.
  • repeat-y — repeat vertically.
  • repeat — the default; repeat in both directions.


When learning about the Box Model, we discovered how borders affect the size of our box. Typically when we add borders to an element with CSS we use a shorthand property that sets the color, width, and style of the border in one line of CSS.

We can set a border for all four sides of a box with border:

.box {
border: 1px solid black;
}

Sizing images

HTML Elements have a natural size, set before they are affected by any CSS. A straightforward example is an image. An image has a width and a height defined in the image file it is embedding into the page. This size is described as the intrinsic size — which comes from the image itself.

If you place an image on a page and do not change its height and width, either using attributes on the tag or CSS, it will be displayed using that intrinsic size.

We can, of course, give elements in our design a specific size. When a size is given to an element (the content of which then needs to fit into that size) we refer to it as an extrinsic size.

In addition to giving things a fixed size, we can ask CSS to give an element a minimum or a maximum size. If you have a box that might contain a variable amount of content, and you always want it to be at least a certain height, you could set the min-height property on it. The box will always be at least this height, but will then grow taller if there is more content than the box has space for at its minimum height.

A common use of max-width is to cause images to scale down if there is not enough space to display them at their intrinsic width while making sure they don't become larger than that width.

As an example, if you were to set width: 100% on an image, and its intrinsic width was smaller than its container, the image would be forced to stretch and become larger, causing it to look pixelated.

If you instead use max-width: 100%, the image is able to become smaller than its intrinsic size, but will stop at 100% of its size.

Form elements

Many form controls are added to your page by way of the <input> element — this defines simple form fields such as text inputs, through to more complex fields added in HTML5 such as color and date pickers. There are some additional elements, such as <textarea> for multiline text input, and also elements used to contain and label parts of forms such as <fieldset> and <legend>.

HTML5 also contains attributes that enable web developers to indicate which fields are required, and even the type of content that needs to be entered. If the user enters something unexpected, or leaves a required field blank, the browser can show an error message. Different browsers are inconsistent in how much styling and customization they allow for such items.

Elements that allow for text input, such as <input type="text">, specific types such as <input type="email">, and the <textarea> element are quite easy to style and tend to behave just like other boxes on your page. The default styling of these elements will differ however based on the operating system and browser that your user visits the site with.

Many of the more complex input types are rendered by the operating system and are inaccessible to styling. You should therefore always assume that forms are going to look quite different for different visitors and test complex forms in a number of browsers.

Reference

  • All the documentation in this page is taken from MDN