iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

CSS Selectors

CSS selectors are patterns that pick elements out of the document so you can style them. The same property applied through different selectors will style different elements.

Common selector types

SelectorPicks…Example
UniversalEvery element.* { box-sizing: border-box; }
TypeAll elements of a given tag name.p { color: #333; }
ClassElements with a matching class..btn { padding: 8px 14px; }
IDThe one element with that id.#hero { height: 80vh; }
AttributeElements with a given attribute.input[type="email"] { … }
Pseudo-classElements in a particular state.a:hover { color: red; }
Pseudo-elementA part of an element.p::first-letter { font-size: 2em; }
GroupingSeveral selectors at once.h1, h2, h3 { font-family: Inter; }

Combinators

Combinators describe the relationship between two selectors:

A B descendant — any B inside an A A > B child — B that is a direct child of A A + B adjacent — B that comes right after A A ~ B general sibling — any B that follows A within the same parent
Fig 1. Four combinators in CSS.
Tip: Reach for classes for almost everything. IDs win specificity battles too easily and make styles hard to override.

Example

Example
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Verdana, sans-serif; }
.box { background: #04AA6D; color: #fff; padding: 20px; border-radius: 6px; }
</style>
</head>
<body>

<h1>CSS Selectors</h1>
<div class="box">Edit the CSS on the left, then click Run &raquo;</div>

</body>
</html>
Try it Yourself »

Exercise

Target every element with class "card" and give it a white background.

{ background: #fff; }

Test yourself

Q1. Which selector targets `<a class="btn">`?
Q2. What does `ul > li` select?
Q3. Which selector type has the highest baseline specificity?

Discussion

Loading…