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 allh1elementsbody- selects thebodyelement (there should only be one)p- selects allpelements
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 allaelements within elements with the classsidebarul li- select alllielements withinulelementsp .highlight- select all elements with the classhighlightwithinpelements
If you list two selectors with a comma between them, this selects elements that match either selector.
h1, h2- selects allh1andh2elements.notice, .warning- selects all elements with either the classnoticeorwarningul .selected, ol .selected- select all elements with the classselectedwithinulorolelements
There are a lot more ways to use selectors. You'll get some practice on the next page.