In the realm of web styling, CSS selectors play a pivotal role in defining how HTML elements are presented to users. Among the most commonly used selectors are class and ID selectors, each serving distinct purposes in the process of styling web pages.
Class Selector:
A class selector in CSS is denoted by a period (.) followed by the class name. It allows developers to apply a specific set of styles to multiple HTML elements that share the same class attribute. Class selectors promote consistency and reusability, enabling developers to efficiently style groups of elements with similar characteristics.
ID Selector:
In contrast, an ID selector is identified by a hash symbol (#) preceding the ID name. Unlike classes, IDs must be unique within a web page. This uniqueness makes ID selectors ideal for targeting and styling individual HTML elements. They offer precise control over styling, ensuring that a particular element stands out distinctly from others on the page.
You can check out the full list of CSS selectors in this article.
Here is a simple example explaining CSS class and ID.
<!-- HTML -->
<div id="gru">
<!-- Gru, the mastermind -->
<img src="gru.png" alt="Gru" />
</div>
<div class="minion">
<!-- Minion 1 -->
<img src="minion1.png" alt="Minion 1" />
</div>
<div class="minion">
<!-- Minion 2 -->
<img src="minion2.png" alt="Minion 2" />
</div>
Example CSS:
/* CSS */
#gru {
/* Styles for Gru's lair */
border: 1px solid red;
color: #fff;
padding: 20px;
}
.minion {
/* Styles for minions */
border: 1px solid green;
padding: 10px;
margin: 10px;
}
Only Class Selector:
In this case, we're applying styles using only a class selector. Classes allow us to apply the same style to multiple elements throughout the document. Here's how it works:
Only ID Selector:
In this case, we're using only an ID selector to apply styles. IDs are unique identifiers for individual elements on a page. Let's see how it's applied:
Edit Example
The above example looks quite wrong, right? IDs happen to be unique selectors. But CSS will parse each DOM element and select it without throwing any errors.
It's Javascript where it becomes more obvious. Even though CSS selectors highlight all the ids, javascript selector will select the first matched item.
Example with javascript selector getElementById: