Quiz
Warm-up from lesson 3-3: which semantic element holds the page's dominant content, the landmark screen readers jump to first?
Anatomy of a CSS rule
CSS exists to keep appearance out of the markup. Before it, styling lived inside HTML itself (font tags on every element), so restyling a site meant editing every page by hand. With CSS, one stylesheet styles a thousand pages, and one edit changes them all — that is the leverage you are about to learn.
CSS is a list of rules. Each rule says which elements (the selector) get which styles (the declarations):
h1 {
color: darkblue;
font-size: 40px;
}- The selector
h1targets everyh1on the page. - Each declaration is a
property: value;pair inside the braces. Do not forget the semicolons.
The usual way to attach CSS is a separate file, linked from the head (remember the skeleton from lesson 2-1):
<head> <link rel="stylesheet" href="styles.css"> </head>
For quick experiments you can also embed rules directly in the head between <style> and </style> tags. The sandbox in this course gives you a dedicated CSS pane instead, which acts like a linked stylesheet.
The three selectors you will use daily
p { color: gray; } /* type: every <p> */
.warning { color: red; } /* class: every element with class="warning" */
#site-title { color: black; } /* id: the ONE element with id="site-title" */And in the HTML:
<h1 id="site-title">Hack University</h1> <p class="warning">This action cannot be undone.</p>
- Type selector: a bare tag name.
- Class selector: a dot plus the class name. An element can carry several classes (
class="warning small"), and one class can be reused on many elements. This is your workhorse. - ID selector:
#plus the id. An id must be unique on the page.
Combine selectors with a comma to share styles: h1, h2 { font-family: Georgia; }. Combine with a space to target descendants: nav a { ... } means links inside the nav.
Quiz
Which CSS selects every element with class="card"?
Style the page using the CSS pane. Write three rules: 1) every p gets color: gray, 2) elements with class="warning" get color: red and font-weight: bold, 3) the element with id="site-title" gets color: darkblue. The HTML pane needs no changes.