CSS linking
We are going to construct a simple web page and style it with CSS. Create the following HTML file, either by copying and pasting, or by retyping (preferred). Use a text editor like Notepad, and save it into a directory you’ve created specifically for this example.
Pick a name for the file—something like style-example.html.
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link rel="stylesheet" type="text/css" href="style.css">
<title>CSS linking</title>
</head>
<body>
<h1>My first CSS example file</h1>
<p>
This is my first attempt at styling HTML files using CSS.
</p>
<p>
This is another paragraph. It should be styled in the same way as the first.
</p>
</body>
</html>
If there are any bits of this you don’t understand, you should go through
my HTML tutorial first—it is much harder
to understand CSS unless you know how HTML works. The only new thing is
the use of the link element directing the browser
to the stylesheet.
If you open your new file in a browser now, it comes up as plain as the other examples in the HTML tutorial.
Now create the following CSS file. You must put it in the same directory
as the HTML file above, and you must call is style.css.
There is nothing special about that name or location, but those are the details
used in the link element. If you call it something else,
or save it somewhere else, the browser won’t find it.
body {
background-color: teal;
color: white;
}
h1 {
color: yellow;
border-left: solid 4px blue;
border-bottom: solid 4px blue;
}
p {
background-color: black;
padding: 3em;
}
Now open the HTML file. If you’ve done everything correctly, and you are using a CSS-capable visual browser, this is how your browser displays it.
Note that the teal background applied to the body
element cascades down to the h1 heading,
a child element of the body. In fact, all properties cascade to child elements
unless overridden. The paragraphs have a black background because we
explicitly specified it—if we hadn’t, they would be teal also. The paragraphs’
white text colour is inherited from the body text colour declaration.
Don’t worry about the new properties used here. Those will get explained in future sections.
Let’s see how to apply styles more specifically than just element-level: for that, we need to look at classes and ID…