We and our partners use cookies to Store and/or access information on a device. We and our partners use data for Personalised ads and content, ad and content measurement, audience insights and product development. An example of data being processed may be a unique identifier stored in a cookie. Some of our partners may process your data as a part of their legitimate business interest without asking for consent. To view the purposes they believe they have legitimate interest for, or to object to this data processing use the vendor list link below. The consent submitted will only be used for data processing originating from this website. If you would like to change your settings or withdraw consent at any time, the link to do so is in our privacy policy accessible from our home page.
Let's start by adding the smaller bottom margin to our ad:
.ad {
margin-bottom: 1em;
}
This takes care of the space below the ad, but what about the space above?
To make a smaller space above the ad, we must somehow override the bottom margin on the proceeding article.
But that's impossible!
There's no way to select proceeding elements in CSS without adding some kind of hook like a class. But adding a class requires either server-side logic or javascript, and both of these options are messy.
Can top margin do any better?
Top margin spacing
Similar to before, let's add the smaller top margin to the ad like this:
.ad {
margin-top: 1em;
}
Now, what about bottom spacing?
To reduce space below the ad we must override the top margin on the article immediately following the ad.
This is something we can do!
We can use the adjacent sibling selector to target the first article after the ad, here's how you can do that:
.ad + article {
margin-top: 1em;
}
You can think of the plus (+) as meaning 'followed immediately by'.
Easy!
Because the space between elements is defined as part of the element after the space we can change this CSS rule depending on the proceeding element.
In other words: we can override styles that follow particular elements.
This is the power of Cascading Style Sheets (CSS).
It's the cascade that makes top margin work while bottom margin fails.
Towards a More General Purpose CSS Rule
Cascading styles are at the heart of this solution.
The process works by styling an element based on its context, and because CSS only cascades in a forward direction, only proceeding elements are parts of any element's context.
But element order is not a visual thing.
One element only proceeds another based on its HTML source order, it does not matter if its rendering position is actually 'above' or 'below'.
This is where our general-purpose CSS principle comes to light.
If a style can be applied to one of many elements, always use the last possible element in the HTML source to allow overriding by context.