Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS selecting a div after a div with a div

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.

like image 565
Big McLargeHuge Avatar asked Nov 17 '11 17:11

Big McLargeHuge


People also ask

How do you select an element after an element in CSS?

If you want to select an element immediately after another element you use the + selector.

How do you target next element in CSS?

The element+element selector is used to select an element that is directly after another specific element.

Can CSS selectors be combined?

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)

How do I select a tag within a div?

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.


1 Answers

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
like image 143
BoltClock Avatar answered Oct 02 '22 13:10

BoltClock