I have 4 divs in a horizontal row. I want to put space between the divs (using margin, I guess?), but the divs overflow their parent container when I do that.
With zero margin, they line up nicely on one line:
<div style="width:100%; height: 200px; background-color: grey;">
<div style="width: 25%; float:left; margin: 0px; background-color: red;">A</div>
<div style="width: 25%; float:left; margin: 0px; background-color: orange;">B</div>
<div style="width: 25%; float:left; margin: 0px; background-color: green;">C</div>
<div style="width: 25%; float:left; margin: 0px; background-color: blue;">D</div>
</div>
Now when I introduce a margin of 5px, the last button wraps:
<div style="width:100%; height: 200px; background-color: grey;">
<div style="width: 25%; float:left; margin: 5px; background-color: red;">A</div>
<div style="width: 25%; float:left; margin: 5px; background-color: orange;">B</div>
<div style="width: 25%; float:left; margin: 5px; background-color: green;">C</div>
<div style="width: 25%; float:left; margin: 5px; background-color: blue;">D</div>
</div>
I guess this is because the width attribute, when a percentage, doesn't take the margin into account for the element's total width? What's the right way to do this?
Thanks
A possible idea would be to:
width: 25%; float:left;
from the style of your divsstyle="width: 25%; float:left;"
The advantage with this approach is that all four columns will have equal width and the gap between them will always be 5px * 2.
Here's what it looks like:
.cellContainer {
width: 25%;
float: left;
}
<div style="width:100%; height: 200px; background-color: grey;">
<div class="cellContainer">
<div style="margin: 5px; background-color: red;">A</div>
</div>
<div class="cellContainer">
<div style="margin: 5px; background-color: orange;">B</div>
</div>
<div class="cellContainer">
<div style="margin: 5px; background-color: green;">C</div>
</div>
<div class="cellContainer">
<div style="margin: 5px; background-color: blue;">D</div>
</div>
</div>
I would suggest making the div
s a little smaller and adding a margin of a percentage.
<div style="width:100%; height: 200px; background-color: grey;">
<div style="width: 23%; float:left; margin: 1%; background-color: red;">A</div>
<div style="width: 23%; float:left; margin: 1%; background-color: orange;">B</div>
<div style="width: 23%; float:left; margin: 1%; background-color: green;">C</div>
<div style="width: 23%; float:left; margin: 1%; background-color: blue;">D</div>
</div>
http://jsfiddle.net/YJT7q/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With