Identify elements, attributes, classes, and IDs used for styling.
CSS selects HTML elements by their type, class, or ID. These give you ways to choose which elements to style.
A selector is the part of a CSS rule that chooses elements. First, let’s look at the HTML it can match.
An HTML element marks a piece of page content. The p selector in the stylesheet names a paragraph. Open index.html to find the paragraph beside the h1 heading.
p {
color: green;
}In the HTML tab, the paragraph has three parts.
<p> starts the element.</p> ends the element.Together these parts form the paragraph element. In the stylesheet, the selector p uses the tag name without the angle brackets.
The paragraph turns green. The heading keeps its own text color.
An attribute adds information to an element. It appears inside the opening tag, separated from the element name by a space:
<p class="highlight">Track progress and review upcoming milestones.</p>The attribute has two parts:
class identifies the attribute."highlight" supplies its value.The attribute is separate from the paragraph's text. It gives CSS a way to identify this paragraph without changing its element type.
A class is a name in the class attribute. Multiple elements can share the same class. Add the same class wherever the same styling should apply:
.highlight {
background-color: yellow;
}The dot in .highlight tells CSS to match a class:
In HTML, write class="highlight", without the dot.
One element can have several classes, separated by spaces:
<p class="note editorial">Track progress and review upcoming milestones.</p>This paragraph has two classes: note and editorial. A .note rule and an .editorial rule can both select it. The space separates class names; it is not part of either name.
An ID identifies one particular element. Its value must be unique within the document, and an element can have only one ID:
#title {
color: green;
}The # introduces an ID selector. Write id="title" in HTML and #title in CSS. An element can have both an ID and classes, as this heading does. Unlike classes, an ID value cannot be a list of names separated by spaces.
Try to identify the element name, attribute name, attribute value, and two matching selectors before reading the answer:
<h2 id="summary" class="note">Release summary</h2>The element name is h2. The attribute names are id and class; their values are summary and note. .note matches the reusable class, and #summary matches the unique ID. The same element can have both because the class and ID give CSS different ways to identify it.
Now decide which hook fits before writing any CSS: if a heading and a paragraph should share the same style, give both the same class. If one element needs its own name, use an ID. The next lesson shows how to turn those hooks into complete CSS rules.
Try it yourself
HTML + CSS
p selects elements by name.class and id belongs inside an element's opening tag.#.