我有div元素相邻显示:table-cell;。
我想在它们之间设置margin,但是margin: 5px没有效果。为什么?
我的代码:
<div style="display: table-cell; margin: 5px; background-color: red;">1</div>
<div style="display: table-cell; margin: 5px; background-color: green;">1</div>
我有div元素相邻显示:table-cell;。
我想在它们之间设置margin,但是margin: 5px没有效果。为什么?
我的代码:
<div style="display: table-cell; margin: 5px; background-color: red;">1</div>
<div style="display: table-cell; margin: 5px; background-color: green;">1</div>
如果div像这样相邻
<div id="1" style="float:left; margin-right:5px">
</div>
<div id="2" style="float:left">
</div>
这应该有用!
导致
来自MDN文档:
[margin属性]应用于除元素 除表标题、表和内联表以外的表显示类型
换句话说,margin属性不适用于display:table-cell元素。
解决方案
考虑使用border-spacing属性。
请注意,它应该应用于具有display:table布局和border-collapse:分开的父元素。
例如:
HTML
<div class="table">
<div class="row">
<div class="cell">123</div>
<div class="cell">456</div>
<div class="cell">879</div>
</div>
</div>
CSS
.table {display:table;border-collapse:separate;border-spacing:5px;}
.row {display:table-row;}
.cell {display:table-cell;padding:5px;border:1px solid black;}
参见jsFiddle演示
水平和垂直的边距不同
正如Diego Quirós所提到的,border-spacing属性还接受两个值来为水平轴和垂直轴设置不同的边距。
例如
.table {/*...*/border-spacing:3px 5px;} /* 3px horizontally, 5px vertically */
你可以使用内部div来设置边距。
<div style="display: table-cell;">
<div style="margin:5px;background-color: red;">1</div>
</div>
<div style="display: table-cell; ">
<div style="margin:5px;background-color: green;">1</div>
</div>
JS小提琴
表格单元格不尊重边框,但你可以使用透明边框:
div {
display: table-cell;
border: 5px solid transparent;
}
注意:这里不能用百分比…:(
我也在研究如何使用display: table-cell;(以使高度相等),也有左边距。没有任何建议的解决方案对我有效。所以我来了我的转储工作-我只是增加了一个span与display: table-cell;与宽度的大小所要求的空白。虽然不优雅,但很管用。