CSS Selectors
When we want to add styles to parts of our HTML document, we use selectors. These describe what part of the document we want to style.
To select all elements with the same tag, we just use the tag name. Here are some examples:
h1
- selects allh1
elementsbody
- selects thebody
element (there should only be one)p
- selects allp
elements
Sometimes we want to select only a subset of our elements. We can add the class
attribute to HTML tags, like this:
When we use the class
attribute, we can select all elements on the page with that particular class by putting a period in front of the class name. Here are some examples:
.notice
- select all elements with the classnotice
.sidebar
- select all elements with the classsidebar
.pull-quote
- select all elements with the classpull-quote
Note that class names should start with a letter and be made up of letters, numbers, dashes, or underscores. No spaces or other characters should be used.
We can combine these selectors. If you list two selectors with a space in between them, this narrows the list of elements that can be found. The first selector is used to determine what elements to look in and the second is used to select elements within those. Here are some examples:
.sidebar a
- select alla
elements within elements with the classsidebar
ul li
- select allli
elements withinul
elementsp .highlight
- select all elements with the classhighlight
withinp
elements
If you list two selectors with a comma between them, this selects elements that match either selector.
h1, h2
- selects allh1
andh2
elements.notice, .warning
- selects all elements with either the classnotice
orwarning
ul .selected, ol .selected
- select all elements with the classselected
withinul
orol
elements
There are a lot more ways to use selectors. You'll get some practice on the next page.