# Friday, 29 November 2013
 #
 
Back To Basics

A cascading style sheet (CSS) is used to apply styling to an HTML web page. Separating styling from markup provides cleaner markup, easier reuse of styles, and greater flexibility when maintaining a web page.

This article describes the basics of using CSS to applying styles to a web page.

Cascading style sheets are applied to a web page by either enclosing CSS syntax between a beginning and ending STYLE tag or by creating a separate file (typically with a “.CSS” extension) containing CSS syntax and linking that file to the web page, via the LINK tag. The two syntaxes are shown below:

Inline CSS:

<style>
selector {
     style-name: style-value;
}
tag {
     style-name: style-value;
}
#id {
     style-name: style-value;
}
.classname {
     style-name: style-value;
}
</style> 

Link to stylesheet

<LINK REL=StyleSheet  HREF="style.css" TYPE="text/css">

The CSS syntax consists of a set of selectors, followed by curly brackets (“{” and “}”), containing a set of stylename:stylevalue pairs. For example, in the example below:

div {
     background-color: yellow;
} 

The selector is the word “div”. It tells the style sheet to select all div tags on the page and apply the corresponding style (in this case, yellow background color) to each div.

Historically, the most common type of selectors are

  • Text, to identify a tag name and select all tags of that type (e.g., “div”)
  • Text, preceded by “#”, to identify any element on the page with a given ID (e.g., “#Div1”, which selects any element with the attribute id=“Div1”.)
  • Text, preceded by “.”, to identify any elements on the page with a given class applied to them (e.g., “.Class1”, which selects any element with the attribute class= “Class1”).

Examples of each are below:

Select by Tag

Style:

<style> div
{
background-color: yellow;
} </style>

HTML Markup:

<div>Life, the Universe</div>
<div>and Everything!</div>

Output:

image

Select by ID

Style:

<style> #MyDiv
{
background-color: green;
} </style>

HTML Markup:

<div id="MyDiv">Life, the Universe</div>
<div id="YourDiv">and Everything!</div>

Output:

image

Select by Class name

Style:

<style>
.CoolDiv
 {
    background-color: purple;
 }
</style>

HTML Markup:

<div>Life, the Universe</div>
<div class="CoolDiv">and Everything!</div>

Output:

image