CSS Reference

Quick Reference

The :nth-child() selector selects all specified elements that are the nth child of their parent, regardless of all the children’s types.

What this means is that the counting of the child elements does not 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.

So in the example below, we are looking for each second child of the parent and if it’s a paragraph, we are selecting it.

/* selects every HTML paragraph that is the second child of its parent */
p:nth-child(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.