CSS selectors are patterns used to select and style HTML elements. They allow you to apply styles efficiently to multiple elements at once without modifying the HTML structure.
CSS selectors help control the appearance of elements based on their tag name, class, ID, attributes, relationships, and position in the document.
There are several types of selectors in CSS, each serving a different purpose:
*
)This selector applies styles to all elements on the webpage. It is often used for resetting margins and paddings.
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
💡 This ensures a consistent layout across different browsers.
Targets all elements of a specific type. For example, to style all headings (h1
) in a webpage:
h1 {
color: blue;
font-size: 24px;
}
💡 This changes all <h1>
elements to blue and increases their size.
.classname
)Classes allow you to apply the same style to multiple elements by assigning them a class name in HTML.
.red-text {
color: red;
font-weight: bold;
}
💡 In HTML, you can use this class on any element:
<p class="red-text">This text is red and bold.</p>
Classes are reusable, meaning you can apply them to multiple elements on a page.
#idname
)IDs target only one unique element on the page.
h1, p {
text-align: center;
color: darkblue;
}
⚠ IDs should be unique and not repeated on the page.
selector1, selector2
)You can apply the same style to multiple elements at once by separating selectors with a comma.
h1, p {
text-align: center;
color: darkblue;
}
💡 Both <h1>
and <p>
elements will be centered and dark blue.
Selector | Usage |
---|---|
* (Universal) |
Selects all elements |
element |
Styles specific tags like p , h1 , etc. |
.class |
Targets multiple elements with the same class |
#id |
Styles a unique element |
A, B (Group) |
Styles multiple elements at once |
CSS selectors are essential for efficiently styling web pages. The top most used selectors—Universal (*
), Element (tag
), Class (.class
), ID (#id
), and Group (A, B
)—help control the appearance of HTML elements with precision and flexibility.
By understanding and using these selectors effectively, developers can write clean, maintainable, and scalable CSS. These selectors form the foundation for advanced styling techniques, making web design more efficient and structured.
@asadmukhtar