Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flush first and last margin in CSS

Tags:

css

I would like to make the top element (wether it be a p, img, hx or whatever) flush with the top of the parent element while keeping it's normal separation between it's siblings.

For instance, I have a div full of p elements. Each p element has a top and bottom margin, say 10px. Each p element is separated by 20px (10 from the one above and 10 from the one below). The side effect of this is that the first p is pushed down by 10px and the bottom p is pushed up by 10px.

like image 827
David Beck Avatar asked Sep 17 '25 11:09

David Beck


1 Answers

The simplest approach is to use a sibling selector:

p + p {
    margin-bottom: 10px;
    margin-top: 10px;
}

This rule applies to paragraphs only if they come directly after another paragraph. So, this rule doesn't apply to your first paragraph, as it doesn't follow a paragraph.

If you want space between every paragraph, but not before the first and not after the last, use this:

p + p {
    margin-top: 20px;
}
like image 112
Dori Avatar answered Sep 19 '25 00:09

Dori