Monday, March 26, 2012

the id v the class in css...

The difference between an ID and a class is that an ID can be used to identify one element, whereas a class can be used to identify more than one.

Use IDs when there is only one occurence per page. Use classes when there are one or more occurences per page.


In the CSS, a class selector is a name preceded by a full stop (.) and an ID selector is a name preceded by a hash character (#).
So the CSS might look something like:


#top {
 background-color: #ccc;
 padding: 1em
}

.intro {
 color: red;
 font-weight: bold;
}

The HTML refers to the CSS by using the attributes id and class. It could look something like this:


<div id="top">

<h1>Chocolate curryh1>

<p class="intro">This is my recipe for making curry purely with chocolatep>

<p class="intro">Mmm mm mmmmmp>

div>

Grouping

You can give the same properties to a number of selectors without having to repeat them by separating the selectors by commas.
For example, if you have something like:

h2 {
 color: red;
}

.thisOtherClass {
 color: red;
}

.yetAnotherClass {
 color: red;
}
You could make it:

h2, .thisOtherClass, .yetAnotherClass {
 color: red;
}

Nesting

If the CSS is structured well, there shouldn't be a need to use many class or ID selectors. This is because you can specify properties to selectors within other selectors.
For example:

#top {
 background-color: #ccc;
 padding: 1em
}

#top h1 {
 color: #ff0;
}

#top p {
 color: red;
 font-weight: bold;
}
Removes the need for classes or ID's if it is applied to HTML that looks something like this:

<div id="top">

 <h1>Chocolate curryh1>

 <p>This is my recipe for making curry purely with chocolatep>

 <p>Mmm mm mmmmmp>

div>
This is because, by separating selectors with spaces, we are saying 'h1 inside ID top is colour #ff0' and 'p inside ID top is red and bold'.
This can get quite complicated (because it can go for more than two levels, such as this inside this inside this inside this etc.) and may take a bit of practice.

No comments:

Post a Comment