Cascading Style Sheets

From Wikipedia, the free encyclopedia.

Jump to: navigation, search
HTML

Cascading Style Sheets
Character encodings
Layout engine comparison
Dynamic HTML
Font family
HTML editor
HTML element
HTML scripting
Unicode and HTML
Web colors
W3C
XHTML

In computing, Cascading Style Sheets (CSS) is a stylesheet language used to describe the presentation of a document written in a markup language. Its most common application is to style web pages written in HTML and XHTML, but the language can be applied to any application of XML, including SVG and XUL. The CSS specifications are maintained by the World Wide Web Consortium (W3C).

Contents

Overview

CSS is used by both the authors and readers of web pages to define colors, fonts, layout, and other aspects of document presentation. It is designed primarily to enable the separation of document structure (written in HTML or a similar markup language) from document presentation (written in CSS). This separation provides a number of benefits, including improved content accessibility, greater flexibility and control in the specification of presentational characteristics, and reduced complexity of the structural content. CSS is also capable of controlling the document's style separately in alternative rendering methods, such as on-screen, in print, by voice (when read out by a speech-based browser or screen reader) and on braille-based, tactile devices.

CSS Zen garden with the "Paravion" style sheet
Enlarge
CSS Zen garden with the "Paravion" style sheet

CSS can be used with XML, to allow such structured documents to be rendered with full stylistic control over layout, typography, colour, and so forth in any suitable user agent or web browser.

Elements are styled by selecting them with different selectors. Here are some examples:

All elements 
that is, using the * selector
By element name 
e.g. for all 'p' or 'h2' elements
Descendants 
e.g. for 'a' elements that are descendants of 'li' elements (e.g links inside lists) the selector is "li a"
class or id attributes 
e.g. .class and/or #id for elements with class="class" or id="id"
Adjacent elements 
e.g. for all 'p' elements preceded by 'h2' elements, the selector would be "h2 + p"
Direct child element 
e.g. for all 'span' elements inside 'p', but no 'span' elements deeper within the hierarchy, the selector would be "p > span"
By attribute 
e.g. for all <td align="right"> the selector would be 'td[align="right"]'
CSS Zen garden with the "Uncultivated" style sheet
Enlarge
CSS Zen garden with the "Uncultivated" style sheet

In addition to these, a set of pseudo-classes can be used to define further behavior. Probably the best-known of these is :hover, which applies a style only when the user 'points to' the visible element, usually by holding the mouse cursor over it. It is appended to a selector as in a:hover or #elementid:hover. Other pseudo-classes and pseudo-elements are, for example, :first-line, :visited or :before. A special pseudo-class is :lang(c), where the style would be applied on an element only if it is in language "c".

Selectors may be combined in other ways too, especially in CSS 2.1, to achieve greater specificity and flexibility.

CSS information can be provided by:

  • Author style
    • external, i.e. a separate CSS-file referenced from the document
    • embedded in the document
    • inline, overriding the general style just for one occasion
  • User style
    • a local CSS-file specified by the user in the browser options, to be applied on all documents; for the case that author and user style regarding a particular style item differ, the user can specify which should determine the result.
  • User agent style
    • the default style sheet applied by the user agent, e.g. the browser's default presentation of elements.

CSS specifies a cascading order that accords relative weights to rules. When rules from different origins overlap onto a given element, the one with the greatest weight is actually applied.

Advantages of using CSS include:

  • Presentation information for an entire website or collection of pages resides in one place, and can be updated quickly and easily—that is, if a style sheet is imported.
  • Different users can have different style sheets: large print and text readers for example.
  • The document code is reduced in size and complexity, since it does not need to contain any presentational markup.

CSS has a simple syntax, and uses a number of English keywords to specify the names of various style properties.

A style sheet consists of a list of rules. Each rule consists of a selector and a declaration block. A declaration-block consists of a list of semicolon-separated declarations in curly braces. Each declaration itself consists of a property, a colon (:) then a value.

Example:

p {
   font-family: "Garamond", serif;
}
h2 {
   font-size: 110%;
   color: red;
   background: white;
}
.note {
   color: red;
   background: yellow;
   font-weight: bold;
}
p#paragraph1 {
   margin: none;
}
a:hover {
   text-decoration: none;
}

These are five rules, with selectors p, h2, .note, p#paragraph1 and a:hover

An example of a declaration is color: red, where the property color is given the value red.

In the first two rules, the HTML elements p (paragraph) and h2 (level two heading) are being assigned stylistic attributes. The paragraph element will be rendered in Garamond font or, if Garamond is unavailable, some other serif font. The level-two heading element will be rendered in red on a white background.

The third rule shown here defines a CSS 'class', which can be assigned to any document element by using the class attribute. For example:

<p class="note">This paragraph will be rendered in red and bold, with a yellow background.</p>

The fourth rule will affect a p element whose id attribute is set to paragraph1: It will have no margin within its rendering 'box'.

The last rule defines the hover action for a elements. By default in most browsers, a elements are underlined. This rule will remove the underline when the user "hovers" the mouse cursor over these elements, without clicking.

A CSS stylesheet can contain comments; the format is

/* comment */

Finally, to use a CSS stylesheet, save the code in a file like example.css and then either link to it or import it from HTML or XHTML web pages using one of the two following formats:

<link rel="stylesheet" href="example.css" type="text/css" />
<style type="text/css">
   <!--
   @import "example.css";
   //-->
</style>

Note that the ' />' construct in the first example only applies in XHTML; in HTML, just close an empty element such as this with '>'.

To apply a CSS stylesheet to an XML document, add the following processing instruction, as per the XML example below:

<?xml-stylesheet type="text/css" href="example.css"?>

History of CSS

Style sheets have been around in one form or another since the beginnings of SGML in the 1970s. Various browsers included their own style language which could be used to customize the appearance of web documents. Originally, style sheets were targeted towards the end-user; early revisions of HTML did not provide many facilities for presentational attributes, so it was often up to the user to decide how web documents would appear.

As the HTML language grew, it came to encompass a wider variety of stylistic capabilities to meet the demands of web developers. This gave the designer more control over site appearance, but HTML became more complex to write and maintain. Variations in web browser implementations made consistent site appearance difficult, and users had less control over their web browsing experience.

Seeing the need for an improved web presentation system, Håkon Wium Lie proposed Cascading Style Sheets (CSS) in 1994. Bert Bos was at the time working on a browser called Argo which used its own style sheets; the two decided to work together to develop CSS.

Unlike existing style languages like DSSSL and FOSI, CSS allowed a document's style to be influenced by multiple style sheets. One style sheet could inherit or "cascade" from another, permitting a mixture of stylistic preferences controlled equally by the site designer and user.

Håkon's proposal was presented at the "Mosaic and the Web" conference in Chicago, Illinois in 1994, and again with Bert Bos in 1995. Around this time, the World Wide Web Consortium was being established; the W3C took an interest in the development of CSS, and organized a workshop toward that end chaired by Steven Pemberton. This resulted in W3C adding work on CSS to the deliverables of the HTML editorial review board (ERB). Håkon and Bert were the primary technical staff on this aspect of the project, with additional members, including Thomas Reardon of Microsoft, participating as well. By the end of 1996, CSS was ready to become official, and the CSS level 1 Recommendation was published in December.

Development of HTML, CSS, and the DOM had all been taking place in one group, the HTML ERB. Early in 1997, this was split into three Working Groups: HTML WG, chaired by Dan Connolly of W3C, DOM WG, chaired by Lauren Wood of SoftQuad, and CSS WG, chaired by Chris Lilley of W3C.

The CSS Working Group began tackling issues that had not been addressed with CSS level 1, resulting in the creation of CSS level 2, with a first public Working Draft on 4 November 1997. It was published as a W3C Recommendation on 12 May 1998. CSS level 3, which was started in 1998, is still under development as of 2005.

Difficulty with adoption

Although the CSS1 specification was completed in 1996, it would be more than three years before any web browser achieved full implementation of the specification. Internet Explorer 5.0 for the Macintosh, shipped in March of 2000, was the first browser to have full (better than 99 per cent) CSS1 support, surpassing Opera, which had been the leader since its introduction of CSS support fifteen months earlier. Other browsers followed soon afterwards, and many of them additionally implemented parts of CSS2, though as of 2004, no browser has achieved full implementation of CSS2. Properties specific to aural and paged media remain the least well supported.

Even the browsers that did achieve full implementation often did so with a degree of difficulty; many implementations of CSS are fraught with inconsistencies, bugs and other quirks. Authors have commonly had to use hacks and workarounds in order to obtain consistent results across web browsers and platforms. One of the most well-known CSS bugs is the Internet Explorer box model bug; box widths are interpreted incorrectly in several versions of the browser, resulting in blocks which appear as expected in most browsers, but are too narrow when viewed in Internet Explorer. The bug can be avoided, but not without some cost in terms of functionality.

This is just one of hundreds of CSS bugs that have been documented in various versions of Internet Explorer, Netscape, Mozilla, and Opera, many of which reduce the legibility of documents. The proliferation of such bugs in CSS implementations has made it difficult for designers to achieve a consistent appearance across platforms. Currently there is strong competition between Mozilla's Gecko layout engine, Opera's Presto layout engine, and the KHTML engine used in both Apple's Safari and KDE's Konqueror browsers - each of them is leading in different aspects of CSS. Internet Explorer remains the worst at rendering CSS by standards set down by World Wide Web Consortium as of 2005.

These problems have led the W3C to revise the CSS2 standard into CSS2.1, which may be regarded as something of a working snapshot of current CSS support in HTML browsers. CSS2 properties which no HTML browser had successfully implemented were dropped, and in a few cases, defined behaviours were changed to bring the standard into line with the predominant existing implementations. CSS2.1 became a Candidate Recommendation on February 25, 2004; but was pulled back to Working Draft on June 13, 2005 to fix various issues (in some cases, to match more closely to browser implementation).

Media type

Media Type text/css is registered to use with CSS by RFC 2318.

Use of CSS

CSS is designed to allow the separation of presentation and structure. Prior to CSS, nearly all of the presentational attributes of an HTML document were contained within the HTML code; all font colors, background styles, element alignments, borders and sizes had to be explicitly described, often repeatedly, in the midst of the HTML code. CSS allows authors to move much of that information to a stylesheet, resulting in considerably simpler HTML code. The HTML documents become much smaller and web browsers will usually cache sites' CSS stylesheets. This leads to a reduction in network traffic and noticeably quicker page downloads.

For example, the HTML element h2 specifies that the text contained within it is a level two heading. It has a lower level of importance than h1 headings, but a higher level of importance than h3 headings. This aspect of the h2 element is structural.

Customarily, headings are rendered in decreasing order of size, with h1 as the largest, because larger headings are usually interpreted to have greater importance than smaller ones. Headings are also typically rendered in a bold font in order to give them additional emphasis. The h2 element may be rendered in bold face, and in a font larger than h3 but smaller than h1. This aspect of the h2 element is presentational.

Prior to CSS, document authors who wanted to assign a specific color, font, size, or other characteristic to all h2 headings had to use the HTML font element for each occurrence of that heading type. A heading to be centred on the page in italic, red, Times New Roman might be written:

 <h2 align="center"><font color="red" size="+4" face="Times New Roman,        
  serif"><em>Usage of CSS</em></font></h2>

The additional presentational markup in the HTML made documents more complex, and generally more difficult to maintain; if all level two headings were to be rendered in this style, the markup had to be used for each one separately. Furthermore, a person reading the page with a web browser loses control over the display of the text; if they would rather see the heading in blue, they cannot easily do so, as the site author has explicitly defined the heading color to be used.

With CSS, the h2 element can be used to give the text structure, while the style sheet gives the text its presentational characteristics. The above might be written:

 <h2>Usage of CSS</h2>

While the following block in an accompanying style sheet defines the same style for all default h2 headings across the web site:

h2 {
    text-align: center;
    color: red;
    font: italic large "Times New Roman", serif;
}

Thus, presentation is separated from structure. (It is because of the advantages offered by CSS that the W3C now considers many of the presentational elements and attributes in HTML to be deprecated.) CSS can define color, font, text alignment, size, and also non-visual formatting such as the speed with which a page is read out loud in text readers.

CSS style information can be either attached as a separate document or embedded in the HTML document. Multiple style sheets can be imported, and alternative style sheets can be specified so that the user can choose between them. Different styles can be applied depending on the output device being used. For example, the screen version may be quite different from the printed version. This allows authors to tailor the presentation appropriately for each kind of media. Also, one of the goals of CSS is to allow 'users' a greater degree of control over presentation; users who find the red italic headings difficult to read may apply their own style sheet to the document, and the presentational characteristics will be "cascaded"; the user may override just the red italic heading style, and the remaining attributes will stay the way they are.

See also presentational markup, which gives example CSS code, along with the deprecated tags.

Example of an XHTML document utilizing CSS

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
        <title>XHTML &amp; CSS</title>
        <style type="text/css">
        body {
            background: #fff;
            color: #000;
        }
        h1, h2 {
            font-style: italic;
            font-weight: bold;
            color: blue;
        }
        </style>
    </head>
    <body>
        <h1>This will appear in bold blue italics</h1>
        <p>Normal text.</p>
        <h2 style="color: red; background: green;">
            This will appear in bold red italics on a green background;
            the style for h2 defined above is partly overriden.
        </h2>
        <p>Normal text.</p>
        <h2>This will appear in bold blue italics</h2>
        <p>Normal text.</p>
    </body>
</html>

Example of a user style sheet

File highlightheaders.css containing:

h1 {color: white; background: orange !important; }
h2 {color: white; background: green !important; }

Such a file is stored locally and is applicable if that has been specified in the browser options. "!important" means that it prevails over the author specifications.

Example of applying CSS to 'plain' XML

This example XML file, styled by the CSS stylesheet below, seen in Mozilla Firefox.
Enlarge
This example XML file, styled by the CSS stylesheet below, seen in Mozilla Firefox.

An XML file containing the following - note the xml-stylesheet processing instruction:

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/css" href="css.css"?>
<schedule>
        <date>Tuesday 20 June</date>
        <programme>
                <starts>6:00</starts>
                <title>News</title> 
                With Michael Smith and Fiona Tolstoy.  
                Followed by Weather with Malcolm Stott.
        </programme>
        <programme>
                <starts>6:30</starts>
                <title>Regional news update</title>
                Local news for your area.
        </programme>
        <programme>
                <starts>7:00</starts>
                <title>Unlikely suspect</title>
                Whimsical romantic crime drama starring Janet 
                Hawthorne and Percy Trumpp.
        </programme>
</schedule>

And a separate file called css.css (in the same folder in this case):

@media screen {
        schedule {
                display: block;
                margin: 10px;
                width: 300px;
        }
        date {
                display: block;
                padding: 0.3em;
                font: bold x-large sans-serif;
                color: white;
                background-color: #C6C;
        }
        programme {
                display: block;
                font: normal medium sans-serif;
        }
        programme > * { /* All children of programme elements */
                font-weight: bold;
                font-size: large;
        }
        title {
                font-style: italic;
        }
}

Note the definition of the display property in some cases, in other cases this defaults to 'inline'. Setting this is seldom necessary when styling HTML or XHTML, where such properties are predefined.

CSS pitfalls

CSS may at times be misused, particularly by the author of web documents. Some developers who are accustomed to designing documents strictly in HTML may overlook or ignore the enabling features of CSS. For instance, a document author who is comfortable with HTML markup that mixes presentation with structure may opt to use strictly embedded CSS styles in all documents. While this may be an improvement over using deprecated HTML presentational markup, it suffers from some of the same problems that mixed-markup HTML does; specifically, it entails a similar amount of document maintenance.

CSS shares some pitfalls common with programming languages. In particular, the problem of choosing appropriate names for CSS classes and identifiers may afflict CSS authors. In the attempt to choose descriptive names for CSS classes, authors might associate the class name with desired presentational attributes; for example, a CSS class to be applied to emphasized text might be named "bigred," implying that it is rendered in a large red font. While such a choice of naming may be intuitive to the document author, it can cause problems if the author later decides that the emphasized text should instead be green; the author is left with a CSS class called "bigred" that describes something that is green. In this instance, a more appropriate class name might have been "emphasized," to better describe the purpose or intent of the class, rather than the appearance of elements of that class. In a programming language, such a misuse might be analogous to using a variable name "five" for a variable which contains the value 5; however, if the value of the variable changes to 7, the name is no longer appropriate.

A significant hazard to users of CSS in HTML documents is the proper use of Document Type Definitions. Popular browsers will often interpret CSS in different ways depending on what, if any, DTD is included. This discrepancy is intended to allow authors to write pages that are compatible with older, nonstandard browser versions, but it can often lead to confusing and frustrating problems that may be very difficult to overcome.

Recommendations

The first CSS specification to become an official W3C Recommendation is CSS level 1, published in December 1996. Among its capabilities are support for:

  • Font properties such as typeface and emphasis
  • Color of text, backgrounds, and other elements
  • Text attributes such as spacing between words, letters, and lines of text
  • Alignment of text, images, tables and other elements
  • Margin, border, padding, and positioning for most elements
  • Unique identification and generic classification of groups of attributes

The W3C maintains the CSS1 Recommendation.

CSS level 2 was developed by the W3C and published as a Recommendation in May 1998. A superset of CSS1, CSS2 includes a number of new capabilities, among them the absolute, relative, and fixed positioning of elements, the concept of media types, support for aural style sheets and bidirectional text, and new font properties such as shadows. The W3C maintains the CSS2 Recommendation.

CSS level 2 revision 1 or CSS 2.1 fixes errors in CSS2, removes poorly-supported features and adds already-implemented browser extensions to the specification. While it was a Candidate Recommendation for several months, on 15 June 2005 it was reverted to a working draft for further review.

CSS level 3 is currently under development. The W3C maintains a CSS3 progress report.

CSS experiments

Recently, there has been a trend among web designers to document all their experiments with CSS on a section of their site. Examples include:

These experiments are usually only compatible with browsers that are largely standards compliant.

References

See also

CSS books

Wikibooks
Wikibooks has more about this subject:

CSS discussions

External links

Tutorials

Demonstrations

Resources

Validation

Reference

Browser issues

About the box model

Personal tools