CodeLair website tutorials, articles & scripts

Basic CSS tutorial

Published: 22 October 2004   •   Updated: 17 May 2007   •   Tags: css

Cascading Style Sheets (CSS) are a valuable tool for adding consistency to your web pages. You can change the look of your whole website quickly and with the minimum of fuss. This tutorial will help you get to know CSS and its capabilities - it explains the basic syntax for CSS, lists the most common CSS rules and explains how to apply them to your pages.

What are Cascading Style Sheets? #

Cascading Style Sheets (CSS) add a whole new dimension to the humble web page. They give the designer total control over what, how and where text and images appear on a web page. They enhance the capabilities of HTML. CSS uses styles to set text appearances, layouts and decoration. A style is basically one of a set of properties that carry out a function.

For example, if you wanted all the headings on a page to be 13px Times New Roman, and colored blue, you can set up a style sheet which will tell the browser to change the properties of that particular heading every time it appears on the page. And if you later want to change the headings to a different color or size, you simply change the rule in one place - the style sheet - and every heading across your site will be changed. It’s as easy as that!

CSS does not require any new programming software - you can write it just using a text editor. Note this is for editing plain text so Microsoft Word is not suitable. You can use Notepad on Windows systems, but there are much better options such as Visual Studio Code, Sublime Text or Notepad++ which have syntax highlighting and many other features.

You should also have a basic grasp of HTML - you don’t need to be an expert, but you should know most of the basic tags.

CSS syntax #

CSS rules can be placed in one of three places:

  • Inline - with the HTML tag in the document.
  • In the head - as predefined rules in the head of a page.
  • In an external document - as predefined rules in another file, which can be linked to from all of your web pages.

The former is generally regarded as poor practice, while the latter is usually preferred. Here is the basic syntax for a CSS rule:

selector {
property: value;
}

The selector is used to determine which parts of the page to style. The CSS rules are placed inside curly brackets { }. The property name is followed by a colon, then the value(s) for that property. Each selector can have many rules - each must be separated by a semicolon. The last rule doesn’t need to have a semicolon but it’s recommended for consistency.

There are four basic types of CSS selectors: Elements, Attributes, Classes and IDs, and they can also be combined in various ways. These will be explained in more detail shortly.

Whitespace (spaces and tabs) in between the different parts is ignored, so the above syntax can be formatted in many different ways:

selector{property:value;}

selector { property: value; }

selector
{
property:
value;
}

However, the initial syntax I showed above is the most common. The key thing is to be consistent with the style you choose.

The style tag #

CSS is defined using the <style> tag. Let’s start with the most basic HTML page:

<!doctype html>
<html>
<head>
<title>My page</title>
</head>

<body>

<h1>My page</h1>

<p>Some content on the page</p>

</body>
</html>

The style tag should go inside the <head> element, and the rules go inside the style tag. (Do not worry about the actual rules for now, just learn the syntax.)

<head>
<title>My page</title>
<style>
#rule1 {font: 13px Arial; color: red;}
#rule2 {font: 18px Arial; color: blue;}
</style>
</head>

As stated earlier there are four basic types of selectors which I’ll run through now.

Element selectors #

These are in essence HTML tags. In the basic syntax above, selector is replaced with just the name of the HTML tag (the bit between the < and >). For example, if you wanted to apply a particular style to every paragraph, you would use p, the letter used to define a paragraph in HTML:

p {
font: 13px Arial;
color: red;
}

This rule will set every paragraph to 13px Arial, with a red color. This will work for virtually any HTML tag. A common methodology is to set some base styles to various elements which will apply across the whole of your page, for example setting an overall font size and font face for the document, then for the headings:

body {
font: 13px Arial;
}
h1 {
font: 28px Arial;
}
h2 {
font: 24px Arial;
}
h3 {
font: 20px Arial;
}

Then you can target individual elements using the other selectors below.

Attribute selectors #

These select elements based on their HTML attributes (the attribute="" part). To select them in CSS, use square brackets around the attribute name. So with some HTML like this:

<img src="image.jpg" width="100" height="100" alt="Example">
<img src="image.jpg" width="300" alt="Example">
<img src="image.jpg" width="300" height="100" alt="Example">

The second image doesn’t have a height attribute, so we can select the first and third images using this CSS:

[height] {
border: 2px solid black;
}

We can also select elements with specific values by putting the whole attribute in the brackets:

[width="300"] {
border: 2px solid red;
}

This adds a red border to only the third image.

ID selectors #

An ID selector is a special type of attribute selector. It allows you to apply a rule to one specific element on the web page - that with an id attribute. The CSS selector uses a hash # symbol followed by the ID name. For example with this HTML:

<div id="item1">The first item is 500 pixels wide.</div>
<div id="item2">The second item is 200 pixels wide.</div>
<div id="item3">The third item is 400 pixels wide.</div>

We can target each of the three items individually with this CSS:

#item1 {
width: 500px;
}
#item2 {
width: 200px;
}
#item3 {
width: 400px;
}

Class selectors #

This is probably the most useful CSS rule type. Like IDs it’s a special attribute selector. It is used to apply styles to a set of elements that you decide. The syntax is as follows:

.classname {
color: red;
}

The class name must be preceded by a period (full stop), and you can give the class any name you like, as long as it is one word (i.e. no spaces, although underscores and dashes are allowed). To use this style in the document, you add a class attribute to your HTML tag:

<b class="classname">Bold text</b>

Note that using this will also apply the effects of the HTML tag, i.e. the text will be bold and red in the above example.

It’s also possible to apply multiple classes to an element:

<b class="classname otherclass">Bold text</b>

With this CSS:

.classname {
color: red;
}
.otherclass {
background: lightyellow;
}

You could put both of those rules into the same selector and use just one class. But perhaps the two class names have different meanings and you want to mix and match the classes on different HTML elements

Combining selectors #

CSS selectors can also be combined in various ways. The first way is to apply a set of styles to multiple different selectors at once - separate each with a comma, as below:

h1, h2, h3, h4 {
font: 13px Arial;
color: red;
}

This sets all <h1>, <h2>, <h3>, and <h4> elements to have red, 13px Arial font. Different types of selectors can be mixed:

h1, .bluetext {
color: blue;
}

This will apply to any <h1> tag and any element with a bluetext class, e.g. <p class="bluetext"></p>

Different types of selectors can also be combined as one selector, to be more specific. As element selectors are quite vague, and classes can apply to any element, it’s useful to target an element with a class:

h1.bluetext {
color: blue;
}

Note the lack of space between the two selectors. This will select the h1 only if it has the bluetext class, so <h1 class="bluetext"> becomes blue, but <p class="bluetext"> does not. Multiple classes and/or IDs can be combined:

.classname.otherclass {...}
#item1.bluetext {...}

You can be even more specific and nest tags inside each other, by separating selectors with spaces:

p b {
color: red;
}

This rule will now only work if the <b> tag is used inside the <p> tag. For example, if you type this in the body:

<body>

<b>Bold text</b>
<p>Here is some more <b>bold text</b>, also colored red.</p>

</body>

The first “Bold text” will be bold, but set at the default color. The second “Bold text” will be bold and red because it is nested inside the <p> tag, as stated in our rule. Using the space between selectors is called a descendant selector because it will search any number of levels deep.

A related combinator is the child selector which uses >:

p > b {
color: red;
}

It only selects one level deep, so it will only select the bold text in the second paragraph here:

<b>Bold text</b>
<p>Here is some more <b>bold text</b>, also colored red.</p>
<p>A nested <span>span element with more <b>bold text</b></span>.</p>

Inline CSS rules #

You can define CSS rules inline using the style attribute on any element. The rules stay the same, but are put in quotes as follows:

<p style="font: bold; color: grey;">Text</p>

In general this is discouraged since it encourages a lot of repitition, but it can be useful when using more complex rules, such as positioning.

Linking to an external style sheet #

Another very useful feature of CSS is the ability to link to an external style sheet. You type your rules in a text document, and you can link to it from every page on your site. This is very good when you want to change a rule for your whole site, for example, you want to change the default font. You change the definition in your external style sheet, and the rule is applied to all pages linking to that style sheet. Here’s how you do it:

  1. Open up NotePad, and type all your CSS rules. You do not need to use the <style> tag, just type the rules:

    p b {
    color: red;
    }
    h1, h2, h3, h4 {
    font: 13px Arial;
    color: red;
    }
    #id1 {
    width: 500px;
    }
    .class1 {
    font: bold;
    color: green;
    }
  2. Save this file as a CSS file by adding .css to the end of the filename and click save. Always save it as a name you will remember. A name such as ‘navigation.css’ is much better ‘001qts.css’.

  3. To link to this file in the web page, type the following into the <head> tag:

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

…where filename.css is the filename of the stylesheet. Your styles will then be imported automatically! You can repeat this tag for numerous stylesheets.

CSS rules #

Hopefully you haven’t been frightened off yet! The next part is mostly a reference section. It lists and explains some of the CSS rules you can use to enhance your web pages.

Most CSS rules have two ways to implement certain attributes. Using fonts as an example, you can define the font size using the specific ‘font-size’ property. However, you can also define it in the general ‘font’ property, along with all the other font properties. I will list the specific ones first, then give an example of using the general form. Also note that there is also a ‘none’ option for several properties, which overrides inherited properties (e.g. if one element is nested inside another).

Font & text properties #

Here are several font properties you can use, and the values each one can take:

  • font-family - the name of the font (e.g. Times) or a font type (e.g. sans-serif) or both (e.g. Times,serif)
  • font-style - ‘italic’ or ‘oblique’
  • font-variant - ‘small-caps’
  • font-weight - ‘bold’, ‘bolder’, ‘lighter’ or a number between 100 and 900
  • font-size - point size (pt) or absolute size in pixels (px)
  • line-height - a number (e.g. 2 for double spacing), percentage or point size
  • word-spacing - a length value, points or pixels
  • letter-spacing - a length value again
  • vertical-align - ‘sub’, ‘super’, ‘top’, ‘middle’ or ‘bottom’
  • text-decoration - ‘underline’, ‘overline’, ‘line-through’ or ‘blink’
  • text-align - ‘left’, ‘right’, ‘center’ or ‘justify’
  • text-indent - a length or percentage
  • color - name of a color or a hexadecimal color number

Whew! I’ve got some explaining to do. The property, at the beginning of each line above, is what you put before the colon. The value goes after the colon, and is followed by a semicolon. It’s not as confusing as it sounds. Here’s an example:

#example1 {
font-family: Times,serif;
font-style: italic;
font-weight: bold;
font-size: 14px;
line-height: 2;
letter-spacing: 16px;
color: #FFAD52;
}

Note the following:

  1. The font type (serif, sans-serif etc.) is useful to include in the font-family property because if the font you have specified is not on the system of the person visiting the site, it will be replaced by another font. Including the generic font type means that a similar font will be used.
  2. Font names which contain a space in their name must be enclosed in quote marks, e.g. "Trebuchet MS"
  3. Oblique is basically the same is italic; the only difference is that the computer slants the font to the right when using oblique, whereas italic is a style built in to the font.
  4. There are many different units for lengths, but pixels are the most commonly used. For that we use a number followed by px
  5. Technically, color is not a text property, as it will change the color of borders and horizontal lines within the tag as well, but these can be overridden using their respective functions.
  6. Several of these values can be defined using the ‘font’ property, shown below:
#fontstyles {
font: font-style font-variant font-weight font-size/line-height font-family;
}

Replace each property listed with a value for that property. You do not have to include all the values, however, they must appear in the order listed above. Also note that the line-height must be preceded with a forward slash. For example:

#fontstyles {
font: italic small-caps bold 14px/2 "Trebuchet MS",sans-serif;
}

List properties #

The following are list properties:

  • list-style-type - ‘disc’, ‘circle’, ‘square’, ‘decimal’, ‘lower-roman’, ‘upper-roman’, ‘lower-alpha’ or ‘upper-alpha’
  • list-style-image - ‘url(address of picture)’
  • list-style-position - ‘inside’ or ‘outside’

The general property:

#list1 {
list-style: type position image;
}

If the image does not load for some reason, the list-type will be displayed instead

Background properties #

  • background-color - a color name or hexadecimal
  • background-image - ‘url(address)’
  • background-repeat - ‘repeat’, ‘repeat-x’, ‘repeat-y’ or ‘no-repeat’
  • background-attachment - ‘scroll’ or ‘fixed’
  • background-position - a length value or “plain English” value (see below)

The general property:

#background {
background: color image repeat attachment position;
}

Things to note:

  1. Setting ‘repeat-x’ will make the background repeat across the page (left to right), while ‘repeat-y’ will repeat it down the page.
  2. Setting the attachment to ‘fixed’ means that when you scroll down, the text will move but the background will remain in position.
  3. Plain English values: You need to set two values, one from “top, center, bottom” and one from “left, center, right”. For example center top.

Margin & Border properties #

These properties set margins, padding and borders. To understand these you should think of a CSS element as a box, with text (or whatever) inside it. The border is the square line surrounding the box; the margin is the distance around the outside of the box, i.e. between the border and other content on the page; and the padding is the distance from the border to the content (text) in the element. Here are the various properties:

  • width - a length value or percentage, for the width of the element
  • height - length value, or percentage, for the height of the element
  • margin-top - length value
  • margin-right - length value
  • margin-bottom - length value
  • margin-left - length value
  • padding-top - length value
  • padding-right - length value
  • padding-bottom - length value
  • padding-left - length value
  • border-color - color value
  • border-style - ‘solid’, ‘dotted’, ‘dashed’, ‘double’, ‘groove’, ‘ridge’, ‘inset’, or ‘outset’
  • border-width - a length value, or ‘thin’, ‘medium’ or ‘thick’
  • float - ‘left’ or ‘right’

Things to note:

  1. Although length values can be anything from pts to mm to in (or percentages in some cases), it is best to use pixels, as they are more universal.
  2. Using the border-width property: typing one value will set the border for all four sides; typing two values will set the borders for the top/bottom and left/right pairs respectively; three values set borders for the top, left/right pair, and bottom respectively; and four values set borders for top, right, bottom, and left sides respectively. Got that? This also applies to the border-color property, and the generic margin and padding property values, shown below.
  3. If you use the ‘double’ border style, the border must be at least 3px wide for it to show, as the width value is for the whole border, not each line of the double border. The same applies to ‘groove’, ‘ridge’, ‘inset’, and ‘outset’
  4. The width and height properties do not take into account margins: these will increase the size the element takes up on the screen.
  5. The float property is used to wrap text around other text or images. For example, using float: right; will move that text to the right hand side of the screen, while any remaining text fills up the empty space on the left. The width property should also be used with this.
  6. Several border properties are not supported in either Internet Explorer or Netscape. Use the general border property instead, shown below.

Here are the general rules for margin and padding. The phrases like AllSides should be replaced with actual values.

#margin1 {
margin: AllSides;
}
#margin2 {
margin: TopBottom LeftRight;
}
#margin3 {
margin: Top LeftRight Bottom;
}
#margin4 {
margin: Top Right Bottom Left;
}

#padding1 {
padding: AllSides;
}
#padding2 {
padding: TopBottom LeftRight;
}
#padding3 {
padding: Top LeftRight Bottom;
}
#padding4 {
padding: Top Right Bottom Left;
}

#border {
border: width style color;
}

CSS Positioning #

CSS Positioning, or CSS-P is a great alternative to graphics or tables, as it allows elements to be displayed more quickly and positioned precisely. There are three types of positioning:

  • static - the element displays in the normal position, and cannot be moved.
  • relative - the element flows inline, but can be moved relative to it’s original position.
  • absolute - the element can be positioned anywhere on the page, independent of other elements.

The position type is set with the position property:

#cssP {
position: relative;
}

This on its own will not do anything unless you define where you want the element positioned. To define where the element is on the page, use the top and left properties:

#absolute {
position: relative;
top: 151px;
left: 37px;
}
#relative {
position: relative;
top: -15px;
}

The first rule will display an element 151 pixels from the top of the page and 37 pixels from the left, that is, from the very top left corner of the page. The second moves the text up 15 pixels from where it should be. Note the minus sign.

Conclusion #

That’s all the basic CSS you will need to know as a beginner. However, CSS is constantly being updated with new properties to handle more use cases. We will post more tutorials in future looking at additional properties.

Have fun enhancing your web site!!