Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Child elements with margins within DIVs

Tags:

html

css

xhtml

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.

Image showing the top div (in blue), then a white gap, then the bottom div (in pink). The white gap should not be present.

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?

like image 391
myffical Avatar asked Dec 10 '09 06:12

myffical


People also ask

How do you put a margin inside a 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.

Can a div have margin?

html - Div still has margin even with margin: 0; - Stack Overflow. Stack Overflow for Teams – Start collaborating and sharing organizational knowledge.

Can we set the margins for an element?

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 do you prevent margin collapse?

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.


Video Answer


1 Answers

Add overflow: hidden or overflow: auto to the div

like image 101
K Prime Avatar answered Sep 21 '22 23:09

K Prime