Html 为什么带有“显示:表格单元格”的div 不受保证金影响?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16398823/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why is a div with "display: table-cell;" not affected by margin?
提问by user1929946
I have div
elements next to each other with display: table-cell;
.
我有div
彼此相邻的元素display: table-cell;
。
I want to set margin
between them, but margin: 5px
has no effect. Why?
我想margin
在它们之间设置,但margin: 5px
没有效果。为什么?
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>
回答by Boaz - Reinstate Monica
Cause
原因
From the MDN documentation:
从MDN 文档:
[The margin property] applies to all elements except elements with table display types other than table-caption, table and inline-table
【边距属性】适用于除table-caption、table、inline-table以外的表格显示类型元素以外的所有元素
In other words, the margin
property is notapplicable to display:table-cell
elements.
换句话说,该margin
物业是不适用display:table-cell
的元素。
Solution
解决方案
Consider using the border-spacing
property instead.
考虑改用该border-spacing
属性。
Note it should be applied to a parent element with a display:table
layout and border-collapse:separate
.
请注意,它应该应用于具有display:table
布局和border-collapse:separate
.
For example:
例如:
HTML
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
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
参见jsFiddle 演示
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.
正如 Diego Quirós 所提到的,该border-spacing
属性还接受两个值来为水平轴和垂直轴设置不同的边距。
For example
例如
.table {/*...*/border-spacing:3px 5px;} /* 3px horizontally, 5px vertically */
回答by urmurmur
回答by Chris Happy
Table cells don't respect margin, but you could use transparent borders instead:
表格单元格不尊重边距,但您可以使用透明边框代替:
div {
display: table-cell;
border: 5px solid transparent;
}
Note: you can't use percentages here... :(
注意:您不能在这里使用百分比... :(
回答by user123_456
If you have div next each other like this
如果你有像这样相邻的 div
<div id="1" style="float:left; margin-right:5px">
</div>
<div id="2" style="float:left">
</div>
This should work!
这应该有效!