简体   繁体   中英

Applying a style to an element in CSS depending on the following elements

Short Version: Is there a way to apply a style to an HTML element in CSS only if it is followed by another specific element?

Longer version: The situation is as follows: I am creating content using a help authoring tool (MadCap Flare). Let's say I have the following code:

<ol>
 <li>First li</li>
 <li>Second li</li>
</ol>
<p>A (conditional) paragraph.</p>
<ol>
 <li>Third li</li>
 <li>Fourth li</li>
</ol>

Let's also say the ol has a margin-bottom of 8px, while a li has a margin-bottom of 2px.

The paragraph in the middle might or might not show up in my output, depending on some condition. If the paragraph is there, the margin of the ol will apply. No problem there.

If the paragraph is not there, however, I would like the ol element to have a smaller margin - just the 2px the li-Elements have. In this case, I want it to look like there is just one list.

My dream solution would be to give the ol a margin of 2px if and only if it is followed by another ol. Is there a way to do this with CSS, or will I have to tweak this in some other way?

Why not thinking differently about this and move the margin to the p element instead. So the ol will have a margin-bottom of 2px (the last li ) and in case there is a p element you will add 6px margin to p to have the 8px margin:

 ol { margin:0; } li { margin-bottom:2px; } ol + p { margin-top:6px; margin-bottom:8px; } 
 <ol> <li>First li</li> <li>Second li</li> </ol> <p>A (conditional) paragraph.</p> <ol> <li>Third li</li> <li>Fourth li</li> </ol> <ol> <li>First li</li> <li>Second li</li> </ol> <ol> <li>Third li</li> <li>Fourth li</li> </ol> 

In case it can be any element other than p you can try this:

 ol { margin:0; } li { margin-bottom:2px; } ol + *:not(ol) { margin-top:6px; margin-bottom:8px; } 
 <ol> <li>First li</li> <li>Second li</li> </ol> <section>A (conditional) paragraph.</section> <ol> <li>Third li</li> <li>Fourth li</li> </ol> <ol> <li>First li</li> <li>Second li</li> </ol> <ol> <li>Third li</li> <li>Fourth li</li> </ol> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM