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: