-2

I am learning HTML and CSS from a book and I've faced a problem with connecting between the ids and classes, can any one answer me when to use them?

<p id=”footer”>Please steal this page, it isn’t copyrighted in any way</p>
    <p class="guarantee">

The book said : Giving an element an id is similar to adding an element to a class. The only differences are that the attribute is called “id”, not “class”, an element can’t have multiple ids, and you can’t have more than one element on a page with the same id. but still not understand when to use them :P thanks guys

Andy Holmes
  • 7,817
  • 10
  • 50
  • 83
Wael Assaf
  • 1,233
  • 14
  • 24

5 Answers5

1

classes are generally used to group elements together while ids are used to identify specific elements.

<div class="buttonContainer">
    <button id="home">home</button>
    <button id="about">about</button>
    <button id="contact">contact</button>
</div>

<div class="buttonContainer">
    <button id="email">email</button>
    <button id="query">query</button>
</div>

another example

<div id="header">
    <p class="title">Header Title Here</p>
</id>

<div id="footer">
    <p class="title">Footer Title Here</p>
</div>
TheLovelySausage
  • 3,838
  • 15
  • 56
  • 106
0

The quick answer is that an id should be used to identify a specific element on the page and all ids should be unique. A class, on the other hand can be used to identify multiple elements with the same or similar meaning.

phuzi
  • 12,078
  • 3
  • 26
  • 50
0

You've already mentioned the main differences. But when it comes to the CSS #id selector, there are other things to consider:

See, for example:

<div id="mydiv" class="mydiv"><p>Hello there.</p></div>

CSS:

#mydiv {
color:red;
}

.mydiv {
color:blue;
}

This will yield red colored text because IDs are more specific and thus more relevant to CSS, they are a priority with respect to classes.

fnune
  • 5,256
  • 1
  • 21
  • 35
0

The 'id' attribute should be unique within the same webpage although it is possible to declare more than one element with the same id. There can't be more than one element with a particular 'id'.

There can be multiple elements on the page with the same 'class'. This is useful when you want, for example, apply same CSS style to several elements.

The 'id' is used, for example, in Javascript, for getting an element with a specified id, or when you want to apply a style to only that element.

CBusBus
  • 2,321
  • 1
  • 18
  • 26
Alexiy
  • 1,966
  • 16
  • 18
0

ID's are unique

Each element can have only one ID. Each page can have only one element with that ID.

Classes are NOT unique

You can use the same class on multiple elements. You can use multiple classes on the same element.

Asim Iqbal
  • 148
  • 1
  • 7