Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply style to element, only if a certain element exists next to it

Tags:

html

css

I'm using the <section> tag on several pages, but on ONE page I'm using an <aside> tag that is preceded by the <section> tag.

In the case that I have a <section> immediately followed by an <aside>, I would like to apply a width to both and have the section float left, and the aside float right.

Basically, if I have a <section> and <aside> I want the style to work like this:

section {
    width: 500px;
    float: left;
    padding: 8px;
}

aside {
    padding:8px; 
    width:400px;
    float:right;
}

If I only have the <section> I want it to be like:

section {
    padding: 8px;
}

Is there a way I can do this with either a conditional statement in CSS3, or a pseudo-class, without having to use JavaScript, custom classes, or separate CSS files?

like image 503
Adam Plocher Avatar asked Apr 05 '13 02:04

Adam Plocher


1 Answers

This only works if the <section/> comes after the <aside/>:

<aside>content</aside>
<!-- if there is another node in between, use the '~' selector -->
<section>content</section>

In that case you could use aside ~ section or aside + section:

section {
    padding: 8px;
}
aside + section {
    width: 500px;
    float: left;
}

In all other cases you'll have to use JavaScript because these selectors only work in one direction, top to bottom.

With CSS4 there might be a way using the Subject of a selector with Child combinator, but that's future. This selector was removed from the specification.

like image 176
Linus Caldwell Avatar answered Nov 24 '22 01:11

Linus Caldwell