CSS: selector tutorial
What is CSS Selector
CSS Selector is the CSS syntax that specifies which HTML element to apply styles to.
You can think of CSS Selector as Tag Matchers.
This page introduce the most commonly used patterns.
Example. Most Commonly Used CSS Selectors
/* most common examples of CSS selector syntax */ /* match any p tag */ p { color: red; } /* match p tag that have class bbb */ p.bbb { color: red; } /* match any tag that have class bbb */ .bbb { color: red; } /* match the tag that has id="bbb" */ #bbb { color: red; } /* match p that's direct child of div */ div > p { color: red; } /* match p that's nested in div however deep */ div p { color: red; }
Match Tag Names
Some common examples of setting appearance for HTML elements.
body { font-family: sans-serif; } p { line-height: 1.5; } blockquote { color: navy; } img { margin: 1px; }
Match Class Value
/* matches any tag of class xyz */ .xyz { color: red; }
<div class="xyz">abc</div>
Match Tag Name and Class Value
/* matches any div of class xyz */ div.xyz { color: red; }
<div class="xyz">β¦</div>
Match a Tag's ID
/* matches any tag with id of xyz */ #xyz { color: red; }
<div id="xyz"></div>
Example. Change Link Appearance
Example of removing the underline in links.
a:link { text-decoration: none; } a:visited { text-decoration: none; }
Match Multiple Tags
If you have multiple tags and want them all to have the same appearance, you can use comma.
For example, this:
span.x, span.y, span.z { color: red; }
is equivalent to:
span.x { color: red; } span.y { color: red; } span.z { color: red; }
Match Nested Tags (all levels)
Sometimes, you want to match a tag only if it is nested inside another tag (regardless how many levels deep). You can use the space to specify this, like this:
/* match any span with class xyz, nested at any depth inside a span with class xyz */ div.abc span.xyz { color: red; }
<div class="abc">a <div class="xyz">b</div> c</div>
Match Parent Child Relation
Sometimes you want to match a tag only if it is a immediate child of a given parent tag.
You can use the > to specify a parent-child relationship.
Here is a example:
div > span { color: red; }
CSS Basics
CSS. Selectors
Selector types
- CSS: types of selectors
- CSS: simple selectors
- CSS: compound selectors
- CSS: complex selector (combinator)
Simple selectors
- CSS: type selector (tag name)
- CSS: universal selector (* any tag)
- CSS: class selector (.x)
- CSS: ID selector (#)
- CSS: attribute selector ([x])
Combinators
- CSS: descendant selector (space)
- CSS: child selector (>)
- CSS: adjacent sibling selector (+)
- CSS: subsequent sibling selector (~)
Selector list
Nesting syntax
Special selector
- CSS: :root selector
- CSS: no child selector
- CSS: first child, sibling rank selector
- CSS: nth-child selector
- CSS: pseudo-class selector (:)
- CSS: pseudo-element selector (::)
- CSS: negation selector (:not)
- CSS: βis any ofβ selector (:is, :where)
- CSS: :has descendant selector