Ask coding questions

← Back to all posts
Why won't my CSS nested element rule work?
Yusamac205 (0)

In my CSS code, I created a rule that only affects #banner .content h1 but it simply does not affect the h1 with id="banner" class="content"

Answered by TheDrone7 (547) [earned 5 cycles]
View Answer
Commentshotnewtop
TheDrone7 (547)

It's because you're not using it properly, #banner .content h1 will style the h1 element inside another element with class content which in turn has to be inside another element of ID banner. The correct way to select the element you want to select is h1.content#banner. In the future, refer to https://www.w3schools.com/cssref/css_selectors.asp if you need help with this stuff.

Yusamac205 (0)

@TheDrone7 Thanks for clearing that up, it was confusing me.

TheDrone7 (547)

@Yusamac205 it does that to the best of us.

Vandesm14 (497)

You are using the wrong selector. What you have looks for an element inside a div with the class "content". Like this:

<div id="banner">
    <div class="content">
        <h1>I will be selected</h1>
    </div>
</div>

What you are looking for is:

.banner h1.content

This works because element.class combines the selector so it will only select an element with the class.
This also works with element#id. It only selects `<element id="id">

Please mark this as answered if I helped your problem 👍

Yusamac205 (0)

@Vandesm14 Thanks for explaining TheDrone7's answer in more detail. You helped me understand the "why?" better.