A CSS selector is used to target and apply styles to specific HTML elements.
CSS Selectors
CSS selectors provide a simple method for targeting HTML elements by their id, class, type, attributes, and other criteria.
CSS selectors can be categorized into five groups:
- Simple selectors
- Combinator selectors
- Pseudo-class selectors
- Pseudo-elements selectors
- Attribute selectors
CSS element Selector
The element selector chooses HTML elements using their tag names.
Example
Here, all <p> elements on the page will be left, with white text color and black background-color.
p {
text-align: left;
color: white;
background-color:black;
}
CSS id Selector
The id selector picks a special element using its unique id name in HTML. This id name is unique on a page. To select an element with a certain id, use # followed by the id name.
Example
Now we have applied CSS on the HTML element with id=”school”
#school {
text-align: left;
color: white;
background-color:black;
}
CSS class Selector
The class selector picks out HTML elements that have a particular class name attribute.
To style elements with a specific class, utilize a dot (.) followed by the class name for selecting and applying the class’s styling.
Example
In this example, all HTML elements with class=”school” will be white text-color, left text-align and black background-color.
#school {
text-align: left;
color: white;
background-color: black;
}
CSS Universal Selector
The universal selector (*) targets and selects all HTML elements on the page.
Example
* {
text-align: left;
color: white;
background-color:black;
}
CSS Grouping Selector
The grouping selector selects multiple HTML elements that share the same style definitions.
Consider the following CSS code (where h1, h2, and p elements have identical style definitions).
Example
h1 {
text-align: center;
color: red;
}
h2 {
text-align: center;
color: red;
}
p {
text-align: center;
color: red;
}
Use commas to group selectors and keep your code concise.
Example
h1, h2, p {
text-align: center;
color: red;
}
Note: We welcome your feedback at Easy coding School. Please don’t hesitate to share your suggestions or any issues you might have with the article!