egr103
egr103

Reputation: 3978

How can I style a <section> when it is followed by another <section>?

I'm using section to determine different parts of my page. These sections have a bottom margin of 90px but when a section with the ID of 'clients-full' is created/put in the page, I want whatever section that appears before/above it to have a bottom margin of 0. Can I do this using CSS selectors/pseudo selectors?

Currently, this bit of code styles the section with the ID of 'clients-full' but can it be reversed so I can apply a bottom margin of 0 to the section that is before it?

 section + section#clients-full {
    margin-top: -90px; // Negative margin to get around this problem...not ideal.
 }

Upvotes: 0

Views: 84

Answers (1)

Jukka K. Korpela
Jukka K. Korpela

Reputation: 201588

In CSS as currently defined an implemented, selectors cannot be used in a manner that selects an element depending on what comes after it, only on what comes before it. Well, selectors linke :nth-last-child(...) are an exception in a sense, but they don’t help in a case like this.

Thus, a better approach is to separate the sections by setting a top margin on them, dealing with the first section as a special case if needed (no top margin on it) and perhaps the last section, using :last-ot-type (setting bottom margin on it if needed). Then you can easily handle the case described, simply with #clients-full { margin-top: 0; }.

Upvotes: 1

Related Questions