In CSS, what’s the difference between a class and an ID?

 

This question was asked in an interview with Monster.com

Syntactically the CSS ID and class are very different. You can see the syntactical differences by looking at the CSS code below.

// here the ID "nav" is applied to the ul tag:

ul#nav
{
list-style-type: none;
margin: 0;
padding: 28px;
}

// here the class "question" is applied to the div tag:

div.question{
	font-family: arial;
	font-size: 22px;
	font-weight: bold;
}

// in the html code, a class would be referenced like so:

<div class = "question"> </div>

// in the html code, the nav ID would be referenced like so:

<ul id = "nav"> </ul>

Now that you know what the syntax differences are between an ID and a class, we can explain a bit more about what the differences actually mean. Whereas a class can be used in multiple places on one page, an ID can only be used once. For a given html page, you can only reference the id tag once. But, a class can be referenced mutliple times on the same page.

Because of the uniqueness of an ID, it’s a good idea to use it for elements on the page that you know will not be repeated. So, for instance, using an ID on the top banner of the page makes perfect sense. Classes, however, would be good for html elements like paragraphs or tables that are likely to be repeated throughout your page.

Hiring? Job Hunting? Post a JOB or your RESUME on our JOB BOARD >>

Subscribe to our newsletter for more free interview questions.

Leave a Reply

Your email address will not be published.