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; }
?
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.
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.
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 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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With