Selectors
Targeting HTML Elements with Precision
You've learned that CSS is used to style HTML elements. But how do you tell CSS which elements to style? That's where selectors come in. Selectors are patterns that match against HTML elements in your document, allowing you to target specific elements and apply styles to them.
Think of selectors like search queries. They let you find the specific HTML elements you want to modify, whether it's all the paragraphs, just the headings with a certain class.
Basic Selectors
Here are some of the most common and fundamental CSS selectors:
- Type Selectors (Element Selectors): These select all elements of a specific type (tag name).
- Class Selectors: These select all elements that have a specific class attribute.
Class selectors start with a dot (
.
).
- ID Selectors: These select a single element that has a specific
id
attribute. ID selectors start with a hash symbol (#
). IDs should be unique within a document.
Important: While you can use the same class on multiple elements, IDs must be unique.
Combining Selectors
You can combine selectors to target elements more precisely:
- Descendant Selectors: These select elements that are descendants (children, grandchildren, etc.) of another element. You separate the selectors with a space.
- Child Selectors: These select elements that are direct children of another element.
You use the greater-than sign (
>
).
Attribute Selectors
Attribute selectors allow you to target elements based on the presence or value of their attributes.
- Presence of an Attribute:
- Specific Attribute Value:
Pseudo-Classes
Pseudo-classes are keywords added to selectors that specify a special state of the selected element(s).
:hover
: Applies styles when the user hovers the mouse over an element.
:focus
: Applies styles when the element has focus (e.g., when a user tabs to it).
Specificity: The Key to CSS Conflicts
When multiple CSS rules apply to the same element, the browser needs to determine which rule takes precedence. This is determined by the specificity of the selectors.
Specificity is a complex topic, but here's the basic idea:
- Inline styles have the highest specificity.
- ID selectors have higher specificity than class selectors and attribute selectors.
- Class selectors, attribute selectors, and pseudo-classes have higher specificity than type selectors.
- Type selectors have the lowest specificity.
- The
*
selector has no specificity.
If two selectors have the same specificity, the one that appears later in the source code takes precedence.
Understanding specificity is crucial for debugging CSS and ensuring that your styles are applied correctly.
Practice Makes Perfect
Selectors are the foundation of CSS. The more you practice using them, the better you'll become at targeting the specific elements you want to style. Experiment with different selectors and combinations, and don't be afraid to consult the CSS documentation for more information.
Last updated on