CSS

This section will explore CSS to help us add some style to our pages.

What is CSS?

CSS, which stands for Cascading StyleSheets, is a stylesheet language that is used to specify the styling of an HTML document. This is done by adding properties and values to elements by the way of selectors. Some CSS would look like this:

element {
    property1: value;
    property2: value;
}

As you can see, the element that you want to style is at the top, with the properties enclosed in curly braces ({}). The properties are assigned values by the way of property-name: value; and each line ends with a semi-colon.

CSS can be used to assign styles to elements that have the same tag, class, and/or id, and there are ways to give styling for particular events (for example, what a button temporarily looks like when the user hovers over it).

How to add CSS to HTML

There are 2 ways to add CSS styling to an HTML page. The first is to use in-line styling by way of the <style> tag. In the head of the HTML file, add the opening and closing <style> tags. Then you can place the CSS inside of tag.

The <style> tags can be added anywhere in the html document (as long as it before the elements you want to style), but it is convention to put it in the head of the html document.

The second way is to create a new file, add the CSS there, and save it with the .css file extension. Then it can be imported into the html document using the unpaired <link> tag:

<link rel="stylesheet" href="filepath/nameOfFile.css">

While the first method may seem easier, it is recommended to use the second method to separate out CSS and HTML for easier debugging and as good practice. However sometimes you may just want to add, say 3-4 lines of styling will just 1 or 2 rules to a page, in which case it is okay to use inline styling.

There is a third way, which involves using the style attribute to assign styling to a specific element but this is only used in rare cases when just 1 or 2 properties need to be defined for a very specific element, and even then it is recommended to instead use method 2 and give the element an id attribute.

Next steps

Get the index.html file ready, as we're now going to add some styling to that. Note that we will stick to method 2 of adding CSS (create a new file and import) throughout this guide. First, create a file called styles.css and place it in the same folder as the index.html file. The add the following line to the head of the index.html document:

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

Now, you are ready to add some styling. Let's get started with some core concepts.

Last updated