CSS tutorials

 

Tutorial 02: ID vs. class for divs (and other elements)

First of all, you must know there exist two types of making styled groups of divs (or other elements, the rules is the same). One of them is id, the other is class. What's the difference then?

The general rule is easy: when we use id that means the particular div appears in the HTML only once. Then, in CSS we use # before names of our divs. If the div is to appear more than one we should use class like here:

<div id="content">
    <div class="section">
    
    // here goes first section
    
    </div>
    
    <div class="section">
    
    // here goes second section
    
    </div>
    
    <div class="section">
    
    // here goes third section
    
    </div>
</div> /* closing tag for content div *?

I presented the general rule, and how I learned it. I've seen it's often violated. Is that okay? I don't know. But using multiple divs with the same id won't stop it work properly. However I prefer to stay clean with ids and classess.

Anyway, "section" may be a box of test, a paragraph, anything you need. The elements with the same name will have the same properties. So, in the CSS file we define it as:

div#content {
	background: #040404;
	color: #484848;
	width: 700px;
}
#content div.section {
	background: #121212;
	color: #999999!important; /* just for safety, will be explained in another tutorial */
	margin: 10px;
	width: 500px;
}

So as you can see, the outer div has it's own background color and font, while the inside ones have different ones.

Attention! There's no need to write div everywhere. That's just defining on which element id or class take effect. Instead of div.section you can write p.section but then in the HTML file you change div with class into p with (the same) class. The same you can omit div in div#content it won't be wrong and it wouldn't change anything. But the code this way it more neat.


Making long story short

class - multiple, unlimited uses on one page, initialized in css by a dot (.) before the name
id - one use per page, unique name, initialized by hash (#) before the name