WWW FAQs: What are Cascading Style Sheets (CSS)?


2004-09-29: cascading style sheets are the recommended method of expressing the precise "look and feel" of a web page. By associating a CSS file with a web page, the exact appearance and behavior of every HTML element can be specified.

For instance, if the file main.css contains the following:

a {
text-decoration: none;
}
And the web page page.html contains the following <link> element within its <head> element:
<link href="/main.css" rel="stylesheet" type="text/css">
Then any <a> elements (ordinary links) in the page will not be underlined as they otherwise would be in most browsers.

You can also attach a style to a specific HTML element in the page itself, like so:

<a href="something.html" style="text-decoration: none;">
All modern web browsers support CSS, though CSS support is rarely perfect and testing with a variety of browsers is recommended.

For a complete reference guide to CSS, see the W3 Schools site.

Why do style sheets exist? Why are they separate from HTML?

HTML was always intended to express the content and structure of web pages, rather than their appearance. The original HTML specification offered elements like <cite> (for citations), <a> (anchor, for links), and <p> (paragraph). These express the structure and meaning of a document's parts, but not the way those parts are expected to appear. The look and feel was left up to the programmers of the web browser and the preferences of the reader.

Of course, designers clamored for better control over the appearance of web pages. Various "quick fixes" were introduced, like the <font> and <center> elements, which are now discouraged. The difficulty with elements like these is that they do not express anything about the meaning of the page. What if the user is blind? What if the browser is actually a site-indexing program? Knowing that the text should be "red, and 24 pixels tall" doesn't convey as much to these users as <cite> or <h1>.

A better solution is to let HTML elements express the structure of the document in a way that all users and programs can understand, and let cascading style sheets express the exact appearance the designer prefers for each element -- when the web browser is actually capable of displaying such things.

Legal Note: yes, you may use sample HTML, Javascript, PHP and other code presented above in your own projects. You may not reproduce large portions of the text of the article without our express permission.

Got a LiveJournal account? Keep up with the latest articles in this FAQ by adding our syndicated feed to your friends list!