To understand Cascading Style Sheets (CSS) you first need to understand how to write style rules correctly.
Each Style rule has three parts the first is the selector, which informs the rule which element it applies to.
The second part is the is the property and the third part is the value, these two form the style rule itself which does the formatting.
Remembering the sytax, selector methods and all of the property names is half of the battle in learning CSS, and the other half is the inconsistent levels of support for CSS features among browsers, which is improving all the time.
When you are learning CSS or html for that matter using a WYSIWYG such as DreamWeaver can be very helpful, because as you start to write a style it will open a little dialog box containing a list of proerties and values that you can select then the software writes it for you.
This can be really useful especially if you have forgotten what properties or values are avaible for an element.
Another useful program is Macromedia Homesite which has some useful tools and can do the work for you, you can find more information about text editors and WYSIWYG’s and useful links WYSIWYGs
The way in which CSS styles work is to take a definition of attributes and apply them to any tag or tags that matches the selector associated with the definition.
To quickly review, CSS style definitions have the format illustrated in the code example below.
selector { property1: value1; property2: value2;
propertyN: valueN; }
The browser uses the selector to match the elements (tags) in order to apply the style defintion.
The selector for a style can take several different forms making it flexible so it can match almost any use of tags in a document.
 Top of page
The easiest of the selectors to understand is the plain element selector which you may have already seen previously on the Introduction to CSS page.
The code example below illustrates the format of the element selector.
h1 { color: red; }
When the element name is used as the selector this causes all the tags to be formatted using the attributes of the definition.
You can also attach multiple selectors to the same style definition by listing them in the selector area, and separate them with commas.
For instance the definition in the code example below will affect all the heading tags from <h1> to <h4> in the document.
h1,h2,h3,h4 { color: red; }
 Top of page
The universal selector is an asterisk (*) and it can be used to match any element in a document.
As an extreme example you could use the it to match every tag in a document, which is illustrated in the code example below.
* { color: red; }
This would cause the color: red; attribute to be applied to every tag in the document, although you would very rarely want a style definition to apply to all the elements in a document.
The universal selector can also be used to match other elements of the selector.
For instance, by using the child/descendent matching method of selectors, you could use the universal selector to select everything between the parent element and its descendent.
For example the selectors in the code example below match any <div> tag that is a descendent of a <td> tag that is a descendent of a <tr> tag.
tr td div { color: red; font–style: italic; font–size: 16pt; }
Or you could also use the universal selector to match all the elements between the <tr> tag and the <div> tag as the code example below illustrates.
tr * div { color: red; font–style: italic; font–size: 16pt; }
This technique can be used with any of the selectors.
 Top of page
You can use selectors to match elements by class.
For instance if you had two areas in a document with different backgrounds, one dark and the other light, you would probably want the dark background to have light coloured text and the light background to have dark coloured text
You could use the class attribute in the selected elements to apply the appropriate styles.
To specify a class to match an element name selector you append a period (.) and the class name to the selector.
The style that is defined in the code example below will match any <p> tag with a class attribute name of dark.
p.dark { color: white; }
If the paragraph in the code example below was actually in the dark area of the document the text would be rendered in white, because the class attribute dark has been specified in the paragraphs tag.
<p class="dark">
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nulla massa purus, mollis elementum, malesuada a, fermentum at, justo. Proin et eros vel nisi rutrum volutpat. Aliquam purus ante, sodales sit amet, feugiat nec, luctus placerat, elit.
</p>
You can also use any elements class attribute as the selector to apply a style definition and format the element as the code example below illustrates.
.dark { color: white; }
You can use the universal selector to indicate that all tags that have a certain class should also have the same style applied to them as illustrated in the code example below.
*.dark { color: white; }
However, you can also omit the universal selector, and just specify the class to achieve the same effect.
 Top of page
In the same way that you can match an element using its class attribute, you can also use identifiers (the id attribute) to match the elements in a document.
To match an elements identifier, use the pound sign (#) in the selector.
For example the style definition in the code example below will match any tag with an id attribute of reference.
#reference { border: 2px dotted black; }
 Top of page
It is also possible to match any attribute that has been applied to any element in a document.
The way to achieve this is to specify the elements attribute and the value/s you want to match in the selector.
The form of the selector is illustrated in the code example below.
element[attribute="value"]
For example to match any table in a document with a border attribute set to 3, you could use the selector defined in the code example below.
table[border="3"]
Also you can match elements that contain an attribute, no matter what value the attribute has been set to.
For example the selector in the code example below matches any table in a document with a border attribute.
table[border]
It is possible to combine various selector formats for greater specificity, for example the selector in the code example below will match any table tags with a class attribute of refdata and the border attribute set to 3
table.refdata[border="3"]
It is also possible to stack multiple attribute defintions for greater specificity, each of the attributes is specified in its own bracketed expession.
For instance the selector in the code example below matches tables with a border attribute set to 3 and the width attribute set to 50%
table[border="3"][width="50%"]
There are also two other methods for matching an elements attributes that can be used to match a value in a space or a hyphen separated list in an attributes value.
When matching a value in a space–separated list use ~= instead of the usual equals sign (=).
When matching a value in a hyphen–separated list use |= instead of the usual equals sign (=).
 Top of page
One of the most powerful selector methods that you can employ to match the elements in an html document, is to define selectors that use the relationships between the elements in a document.
Understanding document hierarchy
All of the elements in an html document are related to each other, the heirachy of an html document follows the same nomenclature as family trees, ancestors, parents, children, descendents and siblings.
For example consider the code example below of an html document and the image below which illustrates the same documents hierarchy.
<html>
<head>
<title>Document Hierarchy</title>
</head>
<body>
<div class="divOne">
<h1>Heading One</h1>
<table>
<tr>
<td>Cell One</td><td>Cell Two</td>
</tr>
<tr>
<td>Cell Three</td><td>Cell Four</td>
</tr>
</table>
<p>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Suspendisse pharetra. Integer dui lacus, scelerisque et, fermentum id, condimentum vel, mi. Mauris laoreet suscipit odio. Pellentesque vel tortor quis dolor fringilla vulputate.
</p>
</div>
<div class="divTwo">
<h2>Heading Two</h2>
<p>
Suspendisse quis magna eget mi tristique tincidunt. Praesent metus massa, tincidunt tincidunt, vehicula vitae, faucibus a, elit. Sed ac ligula. Cras justo. Maecenas neque. Integer sem. Etiam ullamcorper aliquam sapien. Sed at dui vitae nunc molestie hendrerit.
</p>
<ol>Ordered List:
<li>
List item one.
</li>
<li>
List item two.
</li>
<li>
List item three.
</li>
</ol>
</div>
</body>
</html>

Graphic representing the hierarchy of the document in the code example above.
Ancestors & Descendents
Ancestors and descendents are elements in an html document that are linked by lineage, also it does not matter what the distance is between the elements.
For instance in the code example and the graphic above the list elements under the divTwo element are descendents of the <body> element, and the <body> element is also their ancestor.
Parents & Children
Parents and children are elements in an html document that are directly connected in lineage.
For example in the graphic and code example above the table rows under the divOne element are the children of the <table> element, and the <table> element is their parent.
Siblings
Siblings are children that share the same direct parent in lineage.
For example in the graphic and the code example above the the list elements under the divTwo element are siblings, they all share the same direct parent the <ol> element.
The heading, paragraph and table elements under the divOne element are also siblings because they all share the same direct parent (divOne) in lineage.
Selectors For Hierarchys
To specify ancestor and descendent relationships between elements in an html document, list all the all the elements that are involved and separate them with spaces.
For example the selector in the code example below matches the list elements under the divTwo element in the graphic and code example above.
div.divTwo li
To specify parent and child relationships between the elements in an html document, list all the elements involved and separate the elements with a right angle bracket (>) or greater than symbol.
For example the selector in the code example below matches the <table> element under the divOne element in the graphic and the code example above.
div.divOne>table
To specify sibling relationships, list all of the elements involved and separate the elements with a plus sign (+).
For example the selector in the code example below matches the <p> element under the divOne element, in the graphic and the code example above.
table+p
 Top of page
Inheritance is the act of aquiring attributes from ones ancestors, in CSS all the foreground properties (color) in an html document are passed down (inherited) to their descendent elements in the document.
For example the the style definition in the code example below would cause all the elements in the document to be rendered in red, because every element in the document is a descendent of the <body> tag.
body { color: red; }
This only applies to foreground properties, and does not apply to background properties such as background colour, image, etc because they are not inherited.
Inheritance is the default action, except when an element has exactly the same attribute defined in a different way.
For example the style definitions in the code example below will cause all the elements in the document to be rendered in blue, and the paragraphs with a class of nored will be rendered in red.
body { color: red; }
p.nored { color: blue; }
Any attributes that are defined that are not in conflict are cumulative and their properties are passed down to descendent elements in the document.
For example the style definition in the code example below will cause any paragraphs with class of emph in the document to be rendered in an italic red 16px font.
body { color: red; }
p.emph { font–style: italic; font–size: 16px; }
 Top of page
CSS also has pseudo–classes that can be used to modify the attributes of the elements in an html document.
Pseudo classes apply to a subset of elements, without the element needing to be tagged with the style.
These classes are typically dynamic and they are tracked by other means than the class attribute.
For example the pseudo classes that can be used to modify the attributes of links or <a> elements in an html document depending upon their status modes (visited, active etc).
When these pseudo classes are used, you do not need to specify the classes in the individual links, the browser determines which link fits into the respective class and applies the style/s appropriately.
Link Styles
The pseudo classes that can be applied to links or <a> elements are listed in the table below.
Pseudo class
|
Purpose
|
:link
|
Unvisited links.
|
:visited
|
Visited links.
|
:active
|
Active links.
|
:hover
|
The link that the pointer is hovering over.
|
:focus
|
Thin link that currently has the user interface focus.
|
The definition in the code example below will cause all of the unvisited links in a document to be rendered in blue, visited in red, and when the mouse pointer is hovering over the link green.
a:link { color: blue; }
a:visited { color: purple; }
a:hover { color: green; }
The order of the definitions is important, because the participation of the link is dynamic, :hover should always be the last definition.
If you reversed the order of :visited and :hover this would cause the :visited links colour attribute to override the :hover colour attribute and the link would not turn green.
The same rule also applies to the :focus pseudo–class, always place the definition last in a list of definitions that affect similar elements.
You can also combine pseudo–classes with other selector methods, if needed.
For example the definition in the first code example below will cause any or all links with a class attribute of important to be rendered in 16px bold font, like the link in the second code example, below the definition.
a:link.important { font–weight: bold; font–size: 16px; }
<a href="http://somesite.com/about/legalstuff.htm"
class="important">disclaimer</a>
The :first–child pseudo class
The :first–child pseudo–class can be used to apply a style/s to the first–child element of a specified element in a document.
This class can be used to add extra space or change the formatting of the :first–child element.
For example if you wanted to indent the first line of text in a paragraph in a div element you could use the style definition in the code example below.
div>p:first–child { text–indent: 25px; }
The :lang pseudo–class
The :lang pseudo–class can be used to construct selectors based on the language setting for specific tags in an html document.
The pseudo–class is useful if your document/s needs to appeal to multiple languages, with different conventions for certain constructs.
For instance the French language uses right angle brackets (< and >) to quote text, and the English language uses quote marks (" and ").
If you had two versions of a document in different languages, you can use the :lang pseudo–class the address the difference, and apply the quote marks appropriately.
The definitions in the code example below will cause the appropriate quote marks to be applied to any text between blockquote tags, depending on the documents lang property (<html lang="en">).
:lang(en) { quotes; ‘"’ ‘"’ "‘" "’"; }
:lang(fr) { quotes: "<<" ">>" "<" ">"; }
blockquote:before { content: open–quote; }
blockquote:after { content: close–quote; }
The :lang selector applies to all of the elements in a document.
However the quotes property is not used by all of the elements, making the effect for most elements transparent.
The last two definitions in the code example above add the quotes to the <blockquote> element.
You can also combine the :before and :after pseudo–elements with other selectors.
For example if you wanted to add quote markes to paragraphs with a class attribute of reference you could use the definition in the code example below.
p.reference:before { content: open–quote; }
p.reference:after { content: close–quote; }
 Top of page
Pseudo–elements provide another way to apply styles dynamically to the elements in an html document.
Apply styles to the first line of an element
The :first–line pseudo–element makes it possible to specify a different style definition for the first line of an element in an html document.
p:first–line { font–size: 16px; font–style: italic; }
The range of properties that the :first–line pseudo–element can effect is limited.
Only the following property groups can be applied using the :first–line pseudo–element.
Font properties, colour properties, background properties, word–spacing, letter–spacing, text–decoration, vertical–align, text–transform, line–height, text–shadow, and clear.
Apply styles to the first letter of an element.
The first–letter pseudo–element can be used to specify a style definition for the first letter of an element in an html document.
This pseudo–element can be used to achieve typographic effects such as dropcaps to make the first letter stand out from the rest of the text in a paragraph.
For example the definition in the code example below will cause the first letter of any paragrapoh with a class attribute of dcap to be rendered in a 3em sized bold font with a 1px border around it.
p.dcap:first–letter { float: left; font–weight: bold; font–size: 3em;
margin: 0px 5px 0px 0px;
padding: 4px 6px 4px 6px;
border: 1px; solid black; }
Before and after text
The :before and :after pseudo–elements can be used to autogenerate content before and after specific elements in an html document.
These pseudo–elements were used in the :lang pseudo–class section above to add quote marks to the beginning and the end of <blockquote> elements
Note the content property used in the code example below the property can be used to assign specific content to content–generating selectors.
In the code examplee below the quote marks are assigned to the before and the after properties, and the <blockquote> element begins and ends with quotes.
blockquote:before { content: ‘"’; }
blockquote:after { content: ‘"’; }
 Top of page
The previous sections have covered how to apply values to properties, it is now time to look at the actual values themselves.
Values can be specified using several different metrics which will depend upon your use and needs.
CSS styles support the metrics listed below.
-
CSS keywords and other properties, such as thick, thin, transparent, ridge etc.
-
Real–world measures.
-
inches (in).
-
centimeters (cm).
-
millimeters (mm).
-
points (pt the points used by CSS2 are equal to 1/72th of an inch.
-
picas (pc) 1 pica is equal to 12 points.
-
Screen measures in pixels (px).
-
Relational to font size (font size (em) or x–height size (ex).
-
Percentages (%).
-
Colour codes (#rrggbb or rgb (r,g,b).
-
Angles.
-
degrees (deg).
-
grads (grad).
-
radians (rad).
-
Time values (seconds (s) and milliseconds (ms)) used with aural style sheets.
-
Frequencies (Hertz (Hz) and kilo Hertz (kHz)) used with aural style sheets.
-
Textual strings.
The units that you use will depend on which properties you are setting in an element and its application to the document.
With regards to relational values (percentages, em etc) the value is calculated on the elements parent elements settings.
The em unit can be used to specify a value that changes as the size of the elements around it change in size.
However always bear in mind that using the em unit can have unpredictable results, so it is best used when you require a relational value rather than an absolute value.
You should now understand how to construct valid CSS style rules using both simple and complex selectors and also the role that inheritance plays in a documents styles, and the different properties and metrics you can specify to format the elements in a document.
|