Rate this page

Flattr this

Add an internal CSS stylesheet to an HTML or XHTML document

Tested with:

Chrome (9, 10, 11, 12, 13, 14)
Firefox (1.0, 1.5, 2.0, 3.0, 3.5, 3.6, 4, 5, 6, 7, 11)
IE (6, 7, 8, 9)
Opera (8, 9, 10, 11)
Safari (4, 5)


To add an internal CSS stylesheet to an HTML or XHTML document


Suppose you are developing a website where each page has deliberately been given a radically different style, to the extent that each one requires a separate stylesheet. Since duplication is not an issue you have chosen to implement these as internal stylesheets, meaning that they are embedded within and downloaded as part of the pages to which they refer.


An internal stylesheet can be added to a document by embedding it within an HTML or XHTML style element. This should have a content type of ‘text/css’ and should be placed within the head of the document:

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>My Homepage</title>
<style type="text/css">
body { font: 12pt normal serif; }

The example above is written as HTML, but the syntax used for the style element is equally acceptable as HTML or XHTML.

This form of the style element, with a required type attribute and CDATA content, was first standardised in HTML version 4. It had previously appeared with unspecified attribute syntax and CDATA content in HTML version 3.2, and with differing syntax and PCDATA content in the draft specification for HTML version 3.0. The syntax adopted by HTML version 4 is also described in early versions of the CSS specification.

On this basis, it would be reasonable to expect that:


Enclosing the stylesheet within an SGML comment

As noted above, very old browsers that do not recognise the style element are likely to render an internal stylesheet as part of the document text. To avoid this, CSS allows the stylesheet to be enclosed within SGML comment delimeters:

<style type="text/css">
body { font: 12pt normal serif; }

The expected behaviour is as follows:

Use of this technique was commonplace when CSS was first introduced, and it was considered essential for websites that needed to render well in a wide variety of browsers. On contemporary websites it is becoming increasingly rare, however there is no particular reason to avoid it if you wish to design defensively.

See also

Further reading

Tags: css | html | xhtml