CSS selectors are patterns used to select and style HTML elements. They are the foundation of CSS, as they determine which elements will be styled and how.
There are several types of CSS selectors, ranging from simple to complex, and each type has a specific use case for targeting HTML elements.
*
targets all elements on the page.div
, p
, h1
..example
.#header
.[type="text"]
.div p
.>
, like div > p
.:hover
.::before
or ::after
.Hereβs an example demonstrating different CSS selectors:
<!DOCTYPE html> <html> <head> <style> /* Type Selector */ p { color: blue; } /* Class Selector */ .highlight { font-weight: bold; } /* ID Selector */ #intro { font-size: 18px; } /* Descendant Selector */ div p { color: green; } /* Child Selector */ div > p { font-style: italic; } /* Pseudo-class Selector */ a:hover { color: red; } /* Pseudo-element Selector */ p::before { content: "Note: "; font-weight: bold; } </style> </head> <body> <div> <p id="intro">This is an introductory paragraph.</p> <p class="highlight">This is a highlighted paragraph.</p> <a href="#">Hover over this link</a> </div> </body> </html>
In this example, different selectors are used to target and style specific elements on the page.
CSS selectors are crucial for styling elements on a web page. Understanding the various types of selectors and their applications will help you write more efficient and effective CSS code.
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!