CSS

Cascading Style Sheets (CSS) consist of sets of style declarations that specify how elements in an HTML page are to be rendered stylistically by the browser.

Each declaration has the following form:

property:value;

A property must be a valid CSS property keyword and the value must be a valid quantity that is dependent on the specified property.  When a declaration is provided with an invalid property or value, the declaration is simply ignored by the CSS engine.

Declarations are grouped in what are called CSS blocks.  Blocks are defined by curly braces  { }.  A block can have 0 or more declarations.  The following is an example of a CSS block that contains 2 declarations.

{
    font-family:Verdana;
    font-size: 24px;
}

Every CSS block is preceded by one or more selectors.  A selector is code that describes a condition that identifies a set of elements on the web page for which the declarations in the CSS block will be applied.  A CSS rule consists of one or more selectors followed by a CSS block.

For example, to apply the declaration in the above block to all of the p elements in a page we would use the following rule.

p {
    font-family:Verdana;
    font-size: 24px;
 }

Incorporating CSS Rules in a HTML Document

There are 3 ways to incorporate CSS rules in a HTML Document:

  1. Declare an external style sheet in the head element using the link element
  2. Embed a set of style rules in the head element of the HTML document using a style element
  3. Define a set of style rules when declaring a HTML element using the element’s style attribute

Link elements are commonly found as nested elements within the head element.  The link element “specifies relationships between the current HTML document and an external resource.”  It is often used to link a CSS stylesheet with the current HTML document.  When used to link a stylesheet, the link element must include a rel attribute and a href attribute The rel attribute defines the relationship between the linked document and the current HTML document and is set to “stylesheet”.  The href attribute specifies the URL of the linked document.  Link elements cannot have content and so should not have a closing tag as shown below.

<link rel="stylesheet" href="stylesheets/navbar.css">
We can also specify a set of CSS rules using the style element in the head element.  For example, the rule given above can be included in a head element as follows:
<head>
    ...
    <style>
        p { 
            font-family:Verdana; 
            font-size: 24px; 
        }
    </style>
    ...
</head>

We can also specify CSS rules when we define a HTML element using the element’s style attribute.  For example, when we use a p element in the HTML document we can specify which font-family to use and which font-size to use when we declare the element as shown below.

...
<p style="font-family:Verdana; font-size: 24px;">In the beginning ...</p>
...

© 2017 – 2020, Eric. All rights reserved.