Selector Combinations
Explore CSS selector combinations to target multiple elements and nested structures in your HTML. Learn how to apply styles to various elements using commas, child selectors, and complex rules. This lesson helps you gain practical skills to efficiently stylize web pages by selecting elements based on tags, classes, and IDs.
We'll cover the following...
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.
Selecting nested elements
Say we have a div element that contains several HTML elements:
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:
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.
Take a moment and answer the following question before proceeding further.
How would you rewrite the CSS for the nested elements above as one single rule?
(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.
True
False
Exercise
The code below includes HTML and partially written CSS. Do the following two tasks:
Apply the
border-bottom(border colour must beblack) CSS property toh1elements with aclassoridattribute.Apply the
font-styleCSS property (with a value ofitalic) topelements with aclassoridattribute.