Declaring CSS in XHTML

So you want to add CSS to your XHTML site. There are a couple of ways to do that.

Declaring CSS in the head section

<html>
<head>
<title>Title of Page</title>
<style type="text/css">
<!--
/* ... Define CSS here ... */
-->
</style>
</head>
<body>
</body>
</html>

Pro: Easy to maintain, if CSS is needed only for that page. You don’t have to hassle with different files.
Con: CSS can be used only for this file.

Declare styles in a seperate file

<html>
<head>
<title>Title of Page</title>
<link rel="stylesheet" type="text/css" href="YOURCSSFILE.css" />
</head>
<body>
</body>
</html>

Pro: CSS can be used everywhere you want. Simply add the link element.
Con: Browser has to load an extra file, which means more HTTP transactions.

Using @import

<html>
<head>
<title>Title of Page</title>
<style type="text/css">
@import url(YOURCSSFILE.css);
</style>
</head>
<body>
</body>
</html>

Same as the above, but has several functions:

url() with quotes (@import url("../file.css");) hides CSS from:

  • Netscape 4.x
  • Win IE 3
  • Win IE 4 (not 4.72)
  • Mac IE 4.01
  • Mac IE 4.5
  • Konqueror 2.1.2
  • Win Amaya 5.1

url() without quotes (@import url(../file.css);) hides CSS from:

  • Netscape 4.x
  • Win IE 3
  • Win IE 4 (reads css only when located in the same directory as html) (not 4.72)

without url() (@import "../file.css";) hides CSS from:

  • Netscape 4.x
  • Win IE 4 and lower
  • Mac IE 4.01
  • Konqueror 2.1.2

Using inline styles

<html>
<head>
<title>Title of Page</title>
</head>
<body>
<h1 style="[specific design for this element]">...</h1>
</body>
</html>

Pro: Style applies only to the specific element. You don’t waste space in a CSS file. Can be easy to handle, because you can quickly see which styles apply to which element.
Con: You’re going to have huge problems when using this method all over your site. You can not control where you have added what, so you need to check every style separatly when modifying your design.

Published by

Julian Bez

Julian Bez

Julian Bez is a software engineer and former startup founder from Berlin, Germany.

  • Devi

    Ease to learn and Good post.