Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Div's class vs id

Tags:

css

class

xhtml

When using divs when is it best to use a class vs id?

Is it best to use class, on say font variant or elements within the html? Then use id for the structure/containers?

This is something I've always been a little uncertain on, any help would be great.

like image 388
Paul Avatar asked Sep 17 '08 15:09

Paul


People also ask

What is the difference between a class and an ID?

The difference between an ID and a class is that an ID is only used to identify one single element in our HTML. IDs are only used when one element on the page should have a particular style applied to it. However, a class can be used to identify more than one HTML element.

What is the difference between div id and class?

Definition. div id is the assignment of the id attribute to a div block to apply styling or interactivity to that specific div block. In contrast, div class is the assignment of a class attribute to a number of div blocks to apply styling or interactivity to a group of div blocks.

What is better class or ID?

The basic rule that you need to keep in mind while using classes and ids in CSS is that, id is used for single elements that appear on the page for only once (e.g. header, footer, menu), whereas class is used for single or multiple elements that appear on the page for once or more than once (e.g. paragraphs, links, ...

What is the difference between id and class in CSS?

When comparing CSS class vs ID, the difference is that CSS class applies a style to multiple elements. ID, on the other hand, applies a style to one unique element. ID is also special in that you can use a special URL to link directly to an element and it's used by JavaScript.


2 Answers

Use id to identify elements that there will only be a single instance of on a page. For instance, if you have a single navigation bar that you are placing in a specific location, use id="navigation".

Use class to group elements that all behave a certain way. For instance, if you want your company name to appear in bold in body text, you might use <span class='company'>.

like image 194
Jim Avatar answered Sep 20 '22 12:09

Jim


The most important thing to understand is that IDs have to be unique: only one element with a given ID should exist within a page. Thus, if you're wanting to refer to a specific page element, that's often the best thing to use.

If you have multiple elements that are in some way similar, you should use the elements class to identify them.

One very useful, surprisingly little known fact is that you can actually apply multiple classes to a single element by putting spaces between the class names. Thus, if you posted a question that was written by the currently logged in user, you might identify it with <div class="question currentAuthor">.

like image 45
Sean McMains Avatar answered Sep 21 '22 12:09

Sean McMains