1

CSS id vs. Class

 2 years ago
source link: https://www.programmerinterview.com/general-miscellaneous/css-id-vs-class/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK