CSS Introduction
CSS, or Cascading Styles Sheets, define how to display HTML. Whereas the HTML defines the content of a document, the style sheet defines the presentation of that content. CSS was added to HTML 4.0 and provided a way to separate the content from the presentation.
CSS Syntax
Rules in CSS are made up of two parts, a selector, and one or more declarations. The following diagram illustrates this syntax:
The selector is the HTML element to be styled.
Each declaration is made up of a property and a value. The property is the style attribute to be changed. The value is what the attribute will be set to. A colon (:) is used to separate the property and its value.
As illustrated in the diagram, declarations end with the semi-colon (;) and are surrounded by curly brackets ({ and }).
CSS Selectors
Styles can be applied to specific HTML elements by specifying the HTML element, then enclosing the styles within curly brackets. The following example shows a style being applied to the
p
element.
p { color:blue; }
In this case, all paragraph elements in the document would have a text color of blue.
There are many different types of selectors that allow great flexibility in applying styles to elements.
CSS Class & ID Selectors
In addition to using the HTML element selectors, custom selectors can also be defined in the form of Class and ID selectors. This allows having the same HTML element, but styled differently depending on its class or ID. An ID selector can be used to identify one element, whereas a class selector can be used to identify more than one element.
In CSS, a class selector is a name preceded by a period (.) and an ID selector is a name preceded by a pound sign (#).
The following CSS code shows a class selector and an ID selector:
.highlight {
color:blue;
font-weight:bold;
}
#codebox {
background-color:#dddddd;
padding:10px;
border-style: solid;
border-width:1px;
}
The following example uses these styles in HTML code:
<div id="codebox">
<p>
'normal' text here
</p>
<p class="highlight">
'highlight' text here
</p>
</div>
CSS Comments
In CSS, a comment starts with /* and ends with */. Comments can span multiple lines, but may not be nested.
The following example shows a single-line and a multi-line comment.
/* A single-line comment */
/* A comment that
spans multiple lines */