CSS ID and Class – What’s the Difference?

CSS ID and Class – What’s the Difference?

CSS ID and Class – What’s the Difference?

CSS IDs (#id) and Classes (.class) are used to apply styles to HTML elements. Here’s how they work:

1. CSS ID (#id)

  • Used to target a single, unique element.
  • Denoted by a # before the name.
  • Each ID must be unique on a page.

Example

<p id="special-text">This is a unique paragraph.</p>
#special-text { color: blue; font-weight: bold; }

✅ Only one element can have id="special-text" on a page.

2. CSS Class (.class)

  • Used to target multiple elements.
  • Denoted by a . before the name.
  • It can be applied to many elements.

Example

<p class="highlight">This is highlighted text.</p> <p class="highlight">Another highlighted text.</p>
.highlight { background-color: yellow; font-size: 18px; }

✅ Multiple elements can have class="highlight".

3. Difference Between ID and Class

FeatureID (#id)Class (.class)
UsageUnique for one elementCan be used on multiple elements
Selector#id.class
SpecificityHigher specificityLower specificity
Best PracticeUsed for unique elements (e.g., #header)Used for reusable styles (e.g., .button)

4. Using ID and Class Together

You can combine IDs and Classes for better styling.

Example

<p id="main-text" class="highlight">This is both unique and reusable.</p>
#main-text { color: red; } .highlight { font-size: 20px; }

#main-text applies red color, and .highlight applies font size.

5. Multiple Classes in One Element

<p class="bold-text italic-text">Styled with multiple classes!</p>
.bold-text { font-weight: bold; } .italic-text { font-style: italic; }

✅ The text will be bold and italic.

6. Nested Selectors (Class inside ID)

#container .title { color: green; }
<div id="container"> <h2 class="title">Styled inside the container</h2> </div>

✅ Only .title inside #container will be green.

Which One Should You Use?

Use class for reusable styles.
Use id for unique elements like navigation or forms.
✔ Avoid using IDs for styling unless necessary (better for JavaScript targeting).

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close