CSS Reference

Quick Reference

The :nth-of-type() selector selects all elements that are the nth child of a specified type, of their parent.

What this means is that the counting of the child elements DOES take into account the type of element. If the first child was an h1, the second an h2, and then the p. The paragraph is the third child, BUT it’s also the first of type (the first p tag). A second p tag after that, would be the :nth-of-type(2). In other words, we’re only counting the types specified.

So in the example below, we are looking for each second paragraph of the parent and selecting it.

/* selects every HTML paragraph that is also the second paragraph of its parent */
p:nth-of-type(2) {
    background-color: black;
}

Additional Info

Selecting Multiple Elements

To select multiple HTML elements with varying ids and classes, separate them with commas.

#intro, #footer, .my_paragraphs, h3 {
     background: white;
}

Increasing Specificity

To be more specific when selecting an HTML element, you can refer to the element and an ancestor element (.grandfather .child or #father .child or .grandfather h1 or any number of combinations). Note that there is no comma between the classes (.grandfather .child) which says you are targeting the class .child and it must have an ancestor with the class .grandfather. You can include as many ancestors as necessary to be as specific as necessary.

.grandfather #son .child p {
     background: white;
}

To select an HTML element that may have multiple classes attached, you can be more specific by including more than one class (or even adding an #id or tag name) to point to that one element: .my_paragraph.secondary_paragraph { }. Note that there are no spaces between the classes because they belong to the same element. This would ONLY select an element that has both classes: .my_paragraph and .secondary_paragraph.

h1.intro, p#footer, h1#header.primary, #sidebar#topper.image {
     background: white;
}

CSS Notes:


We’d like to acknowledge that we learned a great deal of our coding from W3Schools and TutorialsPoint, borrowing heavily from their teaching process and excellent code examples. We highly recommend both sites to deepen your experience, and further your coding journey. We’re just hitting the basics here at 1SMARTchicken.