5

5HTML and CSS: the basics

5.5

The CSS rule structure

CSS is written in rules, each rule has the following:

  • A selector  — (the thing being affected)

  • A declaration — (what we are doing to it)

and it looks like this:

Figure 5.16 - A CSS rule
Figure 5.16   A CSS rule

The selector is the start of the rule; this is the HTML tag that is being formatted, this is followed by a declaration block (this is contained in the braces), the declaration block can hold any number of declarations.

A declaration consists of a property and a value; the property and value are separated by a colon and each declaration is terminated with a semicolon (Figure 5.16).

Let’s expand the CSS rules we have to include a font:

style.css
h1 {
    color: green;
    font-size: 40px;
    font-family: helvetica Neue, arial;
}
Code 5.8   style.css (with font) a

So now we have:

Figure 5.17 - Heading font change with CSS
Figure 5.17   Heading font change with CSS

The <h1> font is now Arial (I’m using a Windows computer that does not have Helvetica Neue installed; it simply uses the next font down the list).

If we applied the same font to the h2 heading, then both h1 and h2 would have a common property (the font-family); CSS allows these properties to be assigned collectively:

style.css
h1, h2 {
    font-family: helvetica Neue, arial;
}
h1 {
    color: green;
    font-size: 40px;
}
h2 {
    color: red;
    font-size: 25px;
}
Code 5.9   style.css (common properties) a

It is generally considered bad practice to duplicate code; the above version of style.css is the better form.

Brackets — quick edit and live preview

Brackets allows the editing of a CSS file from within the HTML document, clicking within a tag in the HTML document and pressing ctrl+e (or right click and select quick edit) allows a new CSS rule to be created in the open CSS document (just click new rule).

In the same way that clicking in an HTML element highlights that element in live preview. Clicking inside the declaration block of a CSS rule (inside the braces) also highlights all the associated elements in live preview.

CSS can of course modify the paragraph text, add the following:

style.css
p {
   font-family: helvetica Neue, arial;
   text-align:justify;
   font-size: 18px;
}
Code 5.10   style.css (paragraph properties) a

Now all the paragraph text is justified and in Arial:

Figure 5.18 - Paragraph and h2 font change with CSS
Figure 5.18   Paragraph and h2 font change with CSS




End flourish image