I need two consecutive div
elements (with backgrounds) to be touching seamlessly, one below the other. However, this layout breaks when I put a child p
element into the bottom div
. The margins of the p
element force a blank gap between both div
elements. This is strange behavior, as I am expecting the margin of the p
to stay within the content and background area of the div
. It renders the same way on Firefox, Chrome and IE 8.
<div style="background: #ccccff">Top Div</div> <div style="background: #ffcccc"><p>Bottom Div</p></div>
Here's what it looks like.
I could fix this by changing the margins to paddings for the p
element, but then I would also have to do this with header elements, list elements, and any other element I want to use at the start of a div
. That is not desirable.
Could someone enlighten me: what caveat of the box model am I missing? Is there an easy way to fix this, preferably by modifying the style of the div
?
Use the padding css property of the container (div) instead. Padding is the space inside and border of the element, while margin is the space outside the border of the element. Check out box model.
html - Div still has margin even with margin: 0; - Stack Overflow. Stack Overflow for Teams – Start collaborating and sharing organizational knowledge.
The CSS margin properties are used to create space around elements, outside of any defined borders. With CSS, you have full control over the margins. There are properties for setting the margin for each side of an element (top, right, bottom, and left).
How to Avoid Margin Collapse. First, remember that margins should preferably be used to increase the distance between sibling elements, not to create spacing between a child and a parent. If you need to increase space within the Flow layout, reach first for padding if possible.
Add overflow: hidden
or overflow: auto
to the div
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