CSS selectors are patterns used to select the HTML elements you want to style. They form the first part of a CSS rule-set and determine which elements the styles will apply to. You can target elements by their name, ID, class, attributes, and even relationships between elements.
p selects all paragraphs..) prefix, for example .highlight.#) prefix, for example #special.* selects all elements on the page.h1, h2, p targets multiple element types with the same rule.div span (descendant) and ul > li (child) use relationships between elements.A basic CSS rule uses a selector followed by a declaration block:
/* General structure of a CSS rule */
selector {
property: value;
}
Different selector types plug into this same structure. Below are the most common basic selectors.
/* Element, class and ID selectors */
p {
color: blue;
}
.highlight {
background-color: yellow;
}
#special {
font-weight: bold;
}
Here is a simple HTML snippet that uses the selectors above.
<!-- HTML using the CSS selectors above -->
<p>This is a normal paragraph.</p>
<p class="highlight">This paragraph uses a class selector.</p>
<p id="special">This paragraph uses an ID selector.</p>
This is a normal paragraph.
This paragraph uses a class selector.
This paragraph uses an ID selector.
In a real browser with the CSS applied, you would see:
.highlight paragraph with a yellow background.#special paragraph in bold text.Selectors can also target elements based on their relationship in the HTML tree.
/* Descendant and child combinator examples */
div span {
color: green;
}
ul > li {
list-style-type: square;
}
div span selects any <span> that lives inside a <div>, at any nesting level, and colors the text green.
ul > li selects only those <li> that are direct children of a <ul>, and sets their bullet style to squares.
Example structure:
<span> inside a <div> will be green.<ul> will show square bullets..highlight or .notice, so your CSS is easier to understand.h1, h2, p.h1 h2 means “h2 inside h1”. If you want both, use h1, h2 instead.:hover, :first-child, and attribute selectors (for example input[type="text"]) as you get more comfortable.notice and make its text red using a class selector.main-title to an h1 element and change its color to green using an ID selector.li elements inside a ul to have circle bullets using a descendant selector.* to apply margin: 0 to all elements on the page.span elements inside div tags with a light background color.h2 and p in one selector and give them the same font-size or color.li elements that are direct children of a ul using ul > li.input[type="text"] and give those inputs a custom border.:hover pseudo-class to change the background color of a button when the mouse is over it.