CSS Selectors
Discover how to precisely target and style HTML elements using the power of CSS selectors.
What are CSS Selectors?
CSS selectors are patterns used to select the HTML elements you want to style. They are the "S" in CSS, telling the browser exactly which parts of the document your CSS rules should apply to. Mastering selectors is essential for writing efficient and maintainable stylesheets.
🎯 The Goal of a Selector
A selector's job is to find one or more elements in the HTML document and apply the declarations within the CSS rule to them.
Simple Selectors
Simple selectors target elements based on their name, ID, or class.
Element Selector
Selects all instances of a specific HTML element.
/* Styles all <p> elements */ p { color: #4a5568; font-size: 16px; }
Class Selector
Selects all elements with a specific class attribute. A class selector starts with a period
(.
).
/* Styles all elements with class="card" */ .card { border: 1px solid #e2e8f0; padding: 1rem; }
ID Selector
Selects a single, unique element with a specific ID. An ID selector starts with a hash
(#
).
/* Styles the unique element with id="main-header" */ #main-header { text-align: center; font-size: 2rem; }
Combinator Selectors
Combinators define the relationship between two selectors.
Descendant Selector
Selects all elements that are descendants of a specified element. The space character
(
) is the descendant combinator.
/* Styles all <p> elements inside a <div> */ div p { color: #718096; }
Child Selector
Selects all elements that are direct children of a specified element. The child combinator is the
"greater than" sign (>
).
/* Styles all <li> elements that are direct children of <ul> */ ul > li { margin-bottom: 0.5rem; }
Pseudo-classes and Pseudo-elements
These selectors target elements based on a special state or position. They give you fine-grained control over your styles.
Pseudo-classes
Used to select elements that are in a specific state, such as when they are hovered over or
clicked. They start with a single colon (:
).
/* Styles a link when the mouse hovers over it */ a:hover { color: #667eea; text-decoration: underline; }
Pseudo-elements
Used to style a specific part of an element. They are denoted by a double colon
(::
).
/* Styles the first letter of a paragraph */ p::first-letter { font-size: 2rem; font-weight: bold; }