Lessons · HTML and CSS · selectors
Selectors
A bare word selects a tag, a dot selects a class, a hash selects an id, and a space between two means 'inside': .menu a is every link inside something with class menu.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
Selectors are how you point. Point too broadly and a rule leaks across the site; point too narrowly and you write the same rule ten times.
How to think about it
Start with a class. Reach for a descendant selector when the same class should look different in one area. Keep ids for anchors and scripts.
Worked example
<ul id="menu"><li class="item">One</li><li class="item on">Two</li></ul><p class="item">Not in the menu</p>Markup with an id, some classes, and a stray paragraph that shares a class.
.item { color: rgb(0, 0, 200); }Every element with the class, wherever it is: all three go blue.#menu .item { font-weight: bold; }Descendant: only items inside the menu go bold. The paragraph does not.li.on { text-decoration: underline; }Tag and class together, no space: an li that also has class on.Your turn
Select every link inside the footer.
footer { color: grey; }Write a page and watch it render
The trap
A space where there should be none. .card.big means one element with both classes; .card .big means a .big inside a .card. Both are valid, and they select different things.