Gap between empty divs

2019-07-21 09:11发布

I tried to make a grid of divs like this http://jsfiddle.net/hGadw/

<div id="outer1"><!--
    --><div class="inner top left">&nbsp;</div><!--
    --><div class="inner top right">&nbsp;</div><!--
    --><div class="inner bottom left">&nbsp;</div><!--
    --><div class="inner bottom right">&nbsp;</div><!--
--></div>
<br>
<div id="outer2"><!--
    --><div class="inner top left"></div><!--
    --><div class="inner top right"></div><!--
    --><div class="inner bottom left"></div><!--
    --><div class="inner bottom right"></div><!--
--></div>

I did its styling as

* {
    box-sizing: border-box;
    margin:0;
    padding:0;
}
body {
    background-color: black;
}
#outer1, #outer2 {
    width:200px;
    height:200px;
    margin:auto;
    border-radius:50%;
}
.inner {
    height: 50%;
    width:50%;
    display: inline-block;
}
.top.left {
    background-color: green;
    border-radius: 100% 0 0 0;
}
.top.right {
    background-color: #ff3300;
    border-radius: 0 100% 0 0;
}
.bottom.left {
    background-color: darkcyan;
    border-radius: 0 0 0 100%;
}
.bottom.right {
    background-color: darkred;
    border-radius: 0 0 100% 0;
}

The first one worked but the second one has a gap between the upper and lower divs.

Why is the gap appearing?

标签: html css
2条回答
Ridiculous、
2楼-- · 2019-07-21 09:28

The reason is due to not collapsing margins.

“In this specification, the expression collapsing margins means that adjoining margins (no non-empty content, padding, or border areas, or clearance separate them) of two or more boxes (which may be next to one another or nested) combine to form a single margin.”

So, here in your case, empty inline-block elements (no border/content/padding clearance separate them) do not have their margins collapsed.

For more info: http://www.sitepoint.com/web-foundations/collapsing-margins/

Put &nbsp; in the other divs as well

Check this fiddle http://jsfiddle.net/hGadw/3/

<div id="outer1"><!--
    --><div class="inner top left">&nbsp;</div><!--
    --><div class="inner top right">&nbsp;</div><!--
    --><div class="inner bottom left">&nbsp;</div><!--
    --><div class="inner bottom right">&nbsp;</div><!--
--></div>
<br>
<div id="outer2"><!--
    --><div class="inner top left">&nbsp;</div><!--
    --><div class="inner top right">&nbsp;</div><!--
    --><div class="inner bottom left">&nbsp;</div><!--
    --><div class="inner bottom right">&nbsp;</div><!--
--></div>
查看更多
Fickle 薄情
3楼-- · 2019-07-21 09:34

The space that you see is caused by the line-height. This is a CSS property that makes sure te letters from your previuous line don't touch those from te current line. Setting line-height:0 will remove all spaceing between those lines.

#outer1, #outer2 {
    width:200px;
    height:200px;
    margin:auto;
    border-radius:50%;
    line-height:0px;   /*<---- removes spacing between lines*/
}

See: http://jsfiddle.net/qnRQj/1/

查看更多
登录 后发表回答