I have a page with multiple items, which have a 33.33% width to fill up the complete width of the page. However, I want to add a 20px margin between the items (both vertically and horizontally, but vertically is the problem here), but just adding a 20px margin on the right of each 1st and 2nd item in a row, destroys the complete page. (remove the commented-out CSS from the fiddle to see what I mean).
Now, the question: How do I add a 20px margin and make sure all .item
divs keep the same size? I could play with the percentage of the width and adding the removed width of an .item
as a margin, but this would never be a steady 20px, since, well, it's percentages.
HTML
<div id="main">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
<div class="item">5</div>
<div class="item">6</div>
<div class="item">7</div>
<div class="item">8</div>
<div class="item">9</div>
<div class="item">10</div>
<div class="item">11</div>
<div class="item">12</div>
</div>
CSS
#main .item {
height: 100px;
width:33.33%;
float:left;
text-align: center;
}
#main .item:nth-child(3n+1) {
background: red;
}
#main .item:nth-child(3n+3) {
background: yellow;
}
#main .item:nth-child(3n+2) {
background:lightblue;
}
/*.item:nth-child(3n+1), .item:nth-child(3n+2) {
margin-right: 20px !important;
}*/
margin
usepadding
instead. Also make sure you're usingbox-sizing: border-box
on ALL elements. – Rob Scottbox-sizing
? I have never seen that before. Edit: Okay, box-sizing is smart, thanks, very useful for future reference as well. Padding is not an option in my case. – Rvervuurtbox-sizing
makes it so when you definewidth
it adds into accountmargin, padding, and borders
. w/o it, your widths aren't really what you'd expect them to be – Rob Scott