Sams Teach Yourself HTML, CSS & JavaScript Web Publishing in One Hour a Day

(singke) #1
ptg16476052

160 LESSON 8: Using CSS to Style a Site


Including Style Sheets in a Page


Thus far, when I’ve discussed style sheets, I’ve applied them using the style attribute.
For example, I’ve shown how you can modify the font for some text using tags such as
<span> or how you can modify the appearance of a list item by applying a style within an
<li>tag. If you rely on the style attribute of tags to apply CSS, if you want to embolden
every paragraph on a page, you need to put style="font-weight: bold" in every <p>
tag. This is no improvement over just using <p><b> and </b></p> instead. The good
news is that the style attribute is the least efficient method of applying styles to a page or
a site. In this section, I’ll explain more powerful approaches.

Creating Page-Level Styles


First , let’s look at how we can apply styles to our page at the page level. Thus far, you’ve
seen how styles are applied, but you haven’t seen any style sheets. Here’s what one looks
like:
<style type="text/css">
h1 { font-size: x-large; font-weight: bold; }
h2 { font-size: large; font-weight: bold; }
</style>

The <style> tag should be included within the <head> tag on your page. The type attri-
bute indicates the MIME type of the style sheet. text/css is the only value you’ll use.
It’s not required in HTML5, and most designers leave it out. The body of the style sheet
consists of a series of rules. All rules have the same structure:
selector { property1: value1; property2: value2; .. }
Each rule consists of a selector followed by a list of properties and values associated with
those properties. All the properties being set for a selector are enclosed in curly braces, as
shown in the example. You can include any number of properties for each selector, and
they must be separated from one another using semicolons. You can also include a semi-
colon following the last property/value pair in the rule, or not, but best practices recom-
mend that you do.
You should already be familiar with CSS properties and values because that’s what you
use in the style attribute of tags. Selectors are something new. I discuss them in detail in
a bit. The ones I’ve used thus far have the same names as tags. If you use h1 as a selec-
tor, the rule will apply to any <h1> tags on the page. By the same token, if you use p as
your selector, it will apply to <p> tags.
Free download pdf