id vs class css code example
Example 1: difference between id and class in css
/* 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. */
Example 2: css id vs class
In CSS,
=> Differences
ID:
- Each element can have only one ID
- Each page can have only one element with that ID
Class:
- You can use the same class on multiple elements.
- You can use multiple classes on the same element.
=> When to use
ID: Use id for single-use elements
Class: Use classes for multi-use elements
=> Naming convention
- BEM 101: https://css-tricks.com/bem-101/
- Basic: Lower case and hyphenate multiwords. Ids have to be unique and distingu
ishable and classes should be named after what they represent and not what their
styling does.
Example 3: css class and id
Select an element with the ID "id" and the class "class":
#id.class {
}
example:
<div>
<strong id="id" class="class">
Foobar
</strong>
<strong class="class">
Foobar
</strong>
</div>
=> Will select the first <strong> element
Select all elements with the class "class",
which are decendents of a element with an ID of "id":
#id .class {
}
example:
<div id="id">
<strong class="class">Foobar</strong>
</div>
=> Will select the <strong> element
Example 4: css class id
css
.class
#id