Publishers of technology books, eBooks, and videos for creative people

Home > Articles

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

How Is CSS Used?

There are several ways in which style sheets can be associated with an HTML document.

Inline Style

CSS can be added to individual HTML elements as the value of the style attribute. This method is called inline CSS. For example, we can give an individual paragraph a text color of red using this code:

<p style="color: red">

This, however, isn't a good idea. Applying style like this doesn't separate presentation from markup and content, so it's really not much better than using presentational HTML. Furthermore, it's not possible to override inline styles, which makes this method even harder to work with than presentational HTML in some respects.

Embedded CSS

Embedded CSS puts the styles for an HTML document in the document's head, inside a style element:

<style type="text/css">
  p {color: red}

The style element contains a type attribute that tells the browser the type of contents of the element, and must be contained in the head of the element, unlike script elements, which may be contained anywhere in a document.

Embedding CSS is not the best possible way of adding CSS to a page, as it works only on a per page basis, and it too should be avoided in favor of the recommended approach, which we'll look at next.

Linking to External CSS

The recommended technique of adding CSS to an HTML document is to link to one or more CSS files using a link element in the head of the HTML document. This allows us to experience the full benefits of using CSS in place of presentational HTML.

<link rel="stylesheet" href="style/style.css"
type="text/css" />

This link element has three attributes, all of which are important:

  • The first is the rel attribute, which we saw in Chapter 3. It specifies the relationship of the linked file to this one—in this case, that the linked file is a style sheet for this document.
  • The second attribute, href, specifies where the style sheet file is located. We can use a relative or absolute URL (style sheets can even be located on different domains from the HTML document).
  • Lastly, we must also have the type of text/css. This tells the browser what type of style sheet language to expect. Some browsers also support XSLT style sheets, so we want to ensure the browser is aware of what it is getting.

An external style sheet is simply a text file. It usually takes the file extension .css, which will typically ensure that the server serves the file as text/css, the MIME type the browser expects based on the type attribute we set.

  • + Share This
  • 🔖 Save To Your Account