Search⌘ K
AI Features

Selector Combinations

Explore how to select and style multiple HTML elements using CSS selector combinations. Understand grouping selectors with commas and targeting nested elements with child selectors. Practice applying styles to headers, classes, and IDs for more precise control over your webpage's appearance.

Selecting multiple elements

To select multiple elements, separate the selectors by commas:

/* Selecting multiple HTML element types */
h1, p {
  border: 1px solid black;
}

/* Selecting styles to be applied to several classes */
.ingredientsList, .instructionsList {
  font-size: 1.2em;
}

/* Using multiple kinds of selectors*/
h3, .red, #redElement{
  color: red;
}

Exercise

Give a color property (with a value of orange) to all the header elements (elements with the h1 or h2 tags) on the page with a single CSS rule.

Test your learning

Selecting nested elements

Say we have a div element that contains several HTML elements:

HTML
<div>
<h1>Selecting Nested Elements with CSS</h1>
<p>We can specify to only style elements within this div.</p>
<div>
<p>Elements can have any level of nesting and still be selected correctly.</p>
</div>
</div>

In this HTML, there is a div (the parent element) that has three children elements. The nested div also contains a single child. Remember that HTML creates a tree-like structure:

Tree structure of HTML shown above
Tree structure of HTML shown above

To select for only the children of a certain parent element, you must indicate the parent element and then the child element, with a > bracket in between them.

/* select only for h1 elements within div's */
div > h1 {
  border-bottom: 1px solid black;
}

This mechanism can select elements with any level of nesting, by adding an additional selector separated by a space.

Styling nested elements with CSS

Take a moment and answer the following question before proceeding further.

How would you rewrite the CSS rules into one single rule for the above nested elements CSS code?
Technical Quiz
1.

(True or False) Considering that we have two CSS rules in the code above, it is also possible to create a single rule that achieves the same result.

A.

True

B.

False


1 / 1

Exercise

The code below includes HTML and partially written CSS. Do the following two tasks:

  • Apply the border-bottom (border colour must be black) CSS property to h1 elements with a class or id attribute.

  • Apply the font-style CSS property (with a value of italic) to p elements with a class or id attribute.

Test your learning