Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS best practice between margin-top and margin-bottom when both can work?

Tags:

html

css

margin

What is the CSS best practice when you want to give space to an element placed just after a first element.

Asume this html

<div class="a-block">lorem</div>
<div class="another-block">ipsum</div>

Should you use this css

.a-block { margin-bottom: 10px; }

or

.another-block { margin-top: 10px; }

?

like image 961
Benjamin J. Benoudis Avatar asked Apr 05 '15 15:04

Benjamin J. Benoudis


People also ask

Should I use margin top or margin-bottom?

Solution: Always Use Top Margin! The reason is related to the 'C' in CSS. In this article, I'll show you why top margin is better and I'll reveal a deeper CSS principle behind the solution.

Does setting margin top and margin-bottom have an affect on an inline?

Top and bottom margins do not affect inline elements because inline elements flow with content on the page. You can set left and right margins/padding on an inline element but not top or bottom because it would disrupt the flow of content.

Why margin right does not work CSS?

You cannot see the effect of margin-right because the 'width' property of div causes the margin of div to have more than 10px distance from the right wall of the body. Consequently, it causes the margin-right property not to have any visual effect.

Why is my margin-bottom not working?

Why margin-bottom doesn't work in this case. Margin-bottom takes space between self and its next element Where bottom is not , it is realtive to the viewport. Bottom property works if elements position is other than relative.


2 Answers

In my opinion, margin-top in the second block is a better practice.

Indeed, the first div shouldn't take care about others divs since it was the first.

If the second is removed I shouldn't have to remember to remove margin-bottom from the first.

like image 135
Benjamin J. Benoudis Avatar answered Oct 21 '22 12:10

Benjamin J. Benoudis


Using margin-top would eliminate the need of using a next sibling selector. It also removes the need of removing the bottom-margin from the last-child to avoid padding discrepancies when using text in panels or boxes.

like image 40
BraMKJ Avatar answered Oct 21 '22 12:10

BraMKJ