CSS Selectors: A Quick Reference
CSS selectors are the mechanism used to target HTML elements for styling. They act as the link between your markup (HTML) and your design rules (CSS). Without selectors, styles cannot be applied to specific parts of a webpage.
Definition
CSS selectors are the binding mechanism between the Document Object Model (DOM) and the render tree. Browsers parse HTML into a DOM tree and CSS into a CSSOM (CSS Object Model). Selectors are the query engine used to match style rules to DOM nodes during the paint process.
Types of CSS Selectors
Element Selector
The element selector targets all instances of a specific HTML tag. It is useful for defining default styles across a document.
Syntax: Use the tag name directly.
Example: Targeting all
<p>tags.p { font-size: 16px; line-height: 1.5; }
Class Selector
The class selector targets elements with a specific
classattribute. Classes are reusable and can be applied to multiple elements on a single page.Syntax: Use a dot (
.) followed by the class name.Example: Targeting any element with
class="card"..card { border: 1px solid #ccc; padding: 20px; }
ID Selector
The ID selector targets a single element with a specific
idattribute. An ID must be unique within a page, meaning it should only be used once per document.Syntax: Use a hash (
#) followed by the ID name.Example: Targeting an element with
id="header".#header { background-color: #333; color: white; }
Group Selector
Group selectors allow you to apply the same styles to multiple selectors at once. This reduces code redundancy.
Syntax: Separate selectors with a comma (
,).Example: Applying the same font family to
h1,h2, andh3.h1, h2, h3 { font-family: Arial, sans-serif; font-weight: bold; }
Descendant Selectors
Descendant selectors target an element only if it is nested inside another specific element. This allows for context-specific styling.
Syntax: Separate selectors with a space.
Example: Targeting
<a>tags that are inside anavelement.nav a { text-decoration: none; color: blue; }
Selector Priority
When multiple rules apply to the same element, CSS uses a hierarchy called "specificity" to decide which style wins.
The basic order of priority (from highest to lowest) is:
ID Selector (
#id) – Highest priority.Class Selector (
.class) – Medium priority.Element Selector (
tag) – Lowest priority.
