为什么是带有“display:table-cell;”的div不受保证金影响? [英] Why is a div with "display: table-cell;" not affected by margin?
问题描述
我有 display:table-cell;
div
b $ b
我想在它们之间设置 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>
原因
从 MDN文档:
换句话说, margin
属性不适用于 display:table-cell
元素。
解决方案
border-spacing
属性。
请注意,它应该应用于具有 display:table
布局和 border-collapse:separate
。
例如:
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
< pre class =lang-css prettyprint-override>
.table {display:table; border-collapse:separate; border-spacing:5px;}
.row {display:table-row ;}
.cell {display:table-cell; padding:5px; border:1px solid black;}
请参阅 jsFiddle演示
水平和垂直的不同边距
如DiegoQuirós所述, border-spacing
属性也接受两个值来为水平轴和垂直轴设置不同的边距。
p>
.table {/*...*/border-spacing:3px 5px;} / * 3px水平,垂直5px * /
I have div
elements next to each other with display: table-cell;
.
I want to set margin
between them, but margin: 5px
has no effect. Why?
My code:
<div style="display: table-cell; margin: 5px; background-color: red;">1</div>
<div style="display: table-cell; margin: 5px; background-color: green;">1</div>
Cause
From the MDN documentation:
[The margin property] applies to all elements except elements with table display types other than table-caption, table and inline-table
In other words, the margin
property is not applicable to display:table-cell
elements.
Solution
Consider using the border-spacing
property instead.
Note it should be applied to a parent element with a display:table
layout and border-collapse:separate
.
For example:
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;}
See jsFiddle demo
Different margin horizontally and vertically
As mentioned by Diego Quirós, the border-spacing
property also accepts two values to set a different margin for the horizontal and vertical axes.
For example
.table {/*...*/border-spacing:3px 5px;} /* 3px horizontally, 5px vertically */
这篇关于为什么是带有“display:table-cell;”的div不受保证金影响?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!