Reputation: 2503
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>
Upvotes: 229
Views: 195781
Reputation: 19
Here's an excerpt from my "YouLearn.txt" file :
Tags not accepting any/some margins...
...will display as if a margin was specified if you put style='position:relative; top:5%/left:5%'.
(tested with <div>,<span> and even <td>!)
So just try :
<div style='display: table-cell; position:relative; left:5px; top:5px; background-color:red'>1</div>
<div style='display: table-cell; position:relative; left:5px; top:5px; background-color:green'>1</div>
No fancy pants work-around solutions here...
Upvotes: 0
Reputation: 2006
I was also looking how to use display: table-cell;
(so to make equal height) and also have left-margin
. No proposed solutions worked for me. So I came to my dump workaround - I just added one more span with display: table-cell;
with width of the size required margin. Not elegant but it works.
Upvotes: 0
Reputation: 7295
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... :(
Upvotes: 12
Reputation: 20220
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.
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;}
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 */
Upvotes: 327
Reputation: 232
You can use inner divs to set the margin.
<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>
Upvotes: 24
Reputation: 5805
If you have div next each other like this
<div id="1" style="float:left; margin-right:5px">
</div>
<div id="2" style="float:left">
</div>
This should work!
Upvotes: 2