Apply a style to an element only if a specific element exists next to it.

I use the <section> on several pages, but on the same page I use the <aside> , which is preceded by the <section> .

In the case where I have a <section> followed immediately by <aside> , I would like to apply the width to both and leave the float field to the left, and to the side - float right.

Basically, if I have <section> and <aside> , I want the style to work as follows:

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

If I have only <section> , I want this to look like:

 section { padding: 8px; } 

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

+6
source share
1 answer

This only works if <section/> appears after <aside/> :

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

In this case, you can use aside ~ section or aside + section :

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

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

With CSS4, there may be a way to use the Selector Theme with the Child combinator , but this is the future. This selector has been removed from the specification.

+11
source

All Articles