Selector Combinations
Let’s dig into the details of strategies for targeting HTML elements.
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:
<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:
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.
(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.