Assorted CSS fundamentals related to ID’s and Classes.
by David on Aug.01, 2011, under CSS
Style sheets will influence the printed copy of your pages unless specified otherwise. Use the media=”screen” and media=”print” calls to differentiate them. EG.
css” href=”screen.css” />
<link rel=”stylesheet” media=”print” type=”text/css” href=”screen.css” />
The other more recent media type is media=”handheld” (not supported by all browsers) – used for handheld devices.
CSS syntax is made up of a ‘Selector’ (the element or tag you wish to control), followed by at least one declaration comprising of a ‘property’ and its value. EG.
body
{
margin:10px;
}
ID’s: Can only be used once per page. It is a ‘unique identifier’. EG.
<p id=”highlight”> This paragraph has red text. </p>
ID’s are denoted in CSS with the hash (#) symbol. EG.
#highlight
{
color:#F00;
}
Lets say the main
on your page needs to be emphasized with a different color. This calls for a new rule where the selector is difined in the form:
element#name: EG.
h2#title
{
color:#F00;
}
Here the new rule will override the default <h2> colour so long as the h2 is identified with the id=”title” in the XHTML.
Since only one element on each page can be styled by each unique ID, ID’s should therefore be reserved for unique, single-use elements such as header or sidebar or the main navigation or page footer etc. Doing this makes scanning your mark up easier as all ID attributes will denote unique content areas or special regions of the page. ID’s should be avoided when you are likely to multiply something in the future such as images, link styles or paragraphs that may need to be styled in more than one way.
Classes: Can be used an infinite number of times per page, making it very flexible. It means you can re-use the same class in your XHTML if you want to have things styled the same way using just the one line of CSS.
Making good use of Overriding:
An example is as follows:-
p
{
color:#F00;
font-size:12px;
}
.bleached
{
color:#CCC;
}
All paragraphs will still be red by default bu this can be overridden when necessary by identifying an element with the bleached class as shown below:
<p> This paragraph has red text. </p>
<p class=”bleached”> This paragraph has light gray text.</p>
The second paragraph will now be light gray as the colour declaration in bleached overrides the red.
Classes should not be used higgeldy-piggeldy. Make sure you need a class before using one and that the element can’t be targeted by defining a rule for the existing XHTML beforehand. Classes are good for enhancing the behaviour of an ID or controlling elements that belong to a group. It is not recommended that classes be used for main structural elements within a page such as headers and main navigation although they will work.. It just decreases the flexibility of your design and require more work should you need to change your design later.

