Exercises (3/4)
Exercise 6
Let’s compare type, class and ID specificity:
-
Let’s add a class and ID to an existing element. At the beginning of
index.html
, there is an<h5>
element with the author’s name. Give the element a class ofauthor-class
and an ID ofauthor-id
. -
The element now has 3 ways of selecting it, by type, class, and ID.
Add the 3 following rulesets to the bottom of style.css utilizing each of the selectors:
Question
Each of these rules selects the same element in a different way. Which style will win the “specificity war”?
Answer
The id is more specific and will win the war.
Let’s use chaining to select only the <h2>
elements with destinations, and add a style to them.
- In
style.css
, write a CSS selector for<h2>
elements with a class of.destination
. Inside the selector’s curly braces, add this declaration:
This will change the font of the h2 elements that also have the class destination. The last <h2>
element (“More Destinations”) will remain unchanged.
Let’s now use descendant. In index.html
, each destination has a paragraph with a description class below it.
Nested within each description paragraph, is an <h5>
element with the text “Top Attractions”. They’re a little hard to read since they turned yellow. Let’s fix that!
- Navigate to
style.css
. Add a ruleset that uses the descendant combinator to target only the<h5>
descendants of elements with the class.description
. Add a declaration of:
To show how specificity increases with additional selectors, let’s create another ruleset with the descendant combinator and then compare it to a ruleset without:
- In
style.css
, write a ruleset using the descendant combinator to select the<h4>
elements nested in the<li>
elements. Inside of the curly braces, write:
The <h4>
elements under “More Destinations” now appear in gold.
- Now, create a ruleset targeting elements with just the h4 type, and add a declaration of:
Question
Will the <h4>
elements turn blue?
Answer
The elements stay gold because there is a more specific selector for <h4>
elements you wrote in the last step. Because of the more specific CSS selector (li h4), the more general selector of h4 will not take hold.
Finally, let’s try to use multiple selectors:
- In
style.css
, write selectors for the<h5>
and<li>
elements so they will both be styled with the same CSS rule. Apply this style declaration:
Notice that both the <h5>
and <li>
element’s fonts will change, without writing the same CSS declaration twice.