CSS Selectors (Class, ID, Universal, Group)

Introduction CSS selectors define which HTML elements should be styled. Understanding different types of selectors helps in writing efficient and maintainable styles. 1. Universal Selector (*) The universal selector applies styles to all elements. Example: 2. Element Selector Targets all instances of a specific HTML element. Example: 3. Class Selector (.) Targets elements with a […]

  • Post author:
  • Post category: CSS
  • Reading time: 24 mins read
  • Post last modified: April 3, 2025

Introduction

CSS selectors define which HTML elements should be styled. Understanding different types of selectors helps in writing efficient and maintainable styles.

1. Universal Selector (*)

The universal selector applies styles to all elements.

Example:

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
CSS

2. Element Selector

Targets all instances of a specific HTML element.

Example:

h1 {
    color: blue;
}
CSS

3. Class Selector (.)

Targets elements with a specific class.

Example:

.button {
    background-color: green;
    color: white;
}
CSS
<button class="button">Click Me</button>
HTML

4. ID Selector (#)

Targets an element with a unique ID.

Example:

#header {
    font-size: 24px;
}
CSS
<h1 id="header">Welcome</h1>
HTML

5. Group Selector

Styles multiple elements with a single rule.

Example:

h1, h2, p {
    font-family: Arial, sans-serif;
}
CSS

Conclusion

CSS selectors help in efficiently targeting elements for styling. Using the right selector improves readability and performance.

Leave a Reply