Basic selectors
<style>
h1 { color: navy; } /* element */
.highlight { background: yellow; } /* class */
#main-title { font-size: 40px; } /* id */
* { box-sizing: border-box; } /* all elements */
</style>
<h1 id="main-title">Selectors</h1>
<p class="highlight">A highlighted paragraph</p>Use classes for reusable styles. Use ids sparingly, since an id must be unique on the page.
Grouping and combining
h1, h2, h3 { font-family: Georgia, serif; } /* group */
nav a { text-decoration: none; } /* descendant */
ul > li { margin: 4px 0; } /* direct child */
h2 + p { font-weight: bold; } /* next sibling */Pseudo-classes and pseudo-elements
a:hover { color: crimson; }
input:focus { outline: 2px solid dodgerblue; }
li:nth-child(odd) { background: #f3f4f6; }
p::first-line { font-weight: bold; }
button:disabled { opacity: 0.5; }Attribute selectors
input[type="email"] { border-color: green; }
a[target="_blank"]::after { content: " (new tab)"; }Specificity
When two rules conflict, the more specific selector wins:
- Inline style (highest)
- ID selector
- Class, attribute and pseudo-class selectors
- Element selectors (lowest)
If specificity is equal, the rule written later wins.
Tip: Avoid !important. If you need it often, restructure your selectors instead.
Practice
Style a list of links so that every second one has a light background and the link turns a different colour on hover.