hierarchy of nested divs has unintended overlapping borders when using margin and padding

StackOverflow https://stackoverflow.com/questions/21970891

  •  15-10-2022
  •  | 
  •  

Question

When nesting <div>'s their margin's and padding's start to overlap. What I understood from the spec's the margin, border and padding are just part of the space an element takes and each element should stay contained in the content-area of parent <div>.

Clearly I understand wrong, but I hope somebody can explain me right.

Bottom-line: please help me let the thingy's stay inside the top. Preferably in a natural (not too hacky) way.

Thanks for reading and any insight you can share in advance!

The Fiddle:

http://jsfiddle.net/WrasM/2/

The HTML (making sure newlines in HTML don't have any influence):

<!--
--><div class="parent"><!--
    --><div class="top"><!--
        --><div class="thingy">label 1</div><!--
        --><div class="thingy">label 2</div><!--
        --><div class="thingy">label 3</div><!--
    --></div><!--
    --><div class="bottom"><!--
        -->some test content<!--
    --></div><!--
--></div><!--
-->

The CSS:

.parent {  display: block;
           margin: 0px;  padding: 0px;
           border: 3px solid Yellow; }
.top {  display: block;
        margin: 0px;  padding: 0px; }
.thingy {  display: inline;
           margin: 20px;  padding: 10px;
           border: 1px solid DarkBlue; }
.bottom {  display: block;
           margin: 0px;  padding: 0px;
           border: 1px solid DarkBlue; }

The result:

fiddle_result.png

Was it helpful?

Solution

Change .thingy to display:inline-block.

Section 8.3 on this spec page http://www.w3.org/TR/CSS2/box.html says These properties have no effect on non-replaced inline elements. for margin-top and margin-bottom.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top