I have this code on a login page:
<div id="header">
<div id="homeBanner">
...
</div>
</div>
<div id="navigation">
...
</div>
I'd like to select div#navigation but only when it follows div#header that contains div#homeBanner. The reason is I have similar code on a different page:
<div id="header">
<div id="siteBanner">
...
</div>
</div>
<div id="navigation">
...
</div>
I don't want to affect the style of div#navigation when it follows div#header that contains div#siteBanner. Does this make sense?
How do I select div#navigation only when it follows div#header that contains div#homeBanner? I thought it was:
div#header div#homeBanner > div#navigation
... but that doesn't seem to work.
If you want to select an element immediately after another element you use the + selector.
The element+element selector is used to select an element that is directly after another specific element.
A CSS selector can contain more than one simple selector. Between the simple selectors, we can include a combinator. There are four different combinators in CSS: descendant selector (space)
We can use document. querySelector on to select a div and then select an element within it with the given class after that. We just call querySelector on the element with the ID mydiv to select items inside that div.
Problem here is that you're trying to select the sibling of a parent element based on the parent's child, which isn't possible in CSS.
Your best bet is to add a class to #header
(or even body
) based on that information then make use of that class.
For example:
<div id="header" class="home">
<div id="homeBanner">
...
</div>
</div>
<div id="navigation">
...
</div>
With this selector (as mentioned by others, use +
for siblings, not >
for children):
#header.home + #navigation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With