【发布时间】:2015-03-23 21:12:57
【问题描述】:
我有一个包含多个项目的页面,它们有 33.33% 的宽度来填满页面的整个宽度。但是,我想在项目之间添加 20px 的边距(垂直和水平,但这里的问题是垂直),但只需在每行的第一个和第二个项目的右侧添加 20px 的边距,就会破坏整个页面。 (从小提琴中删除注释掉的 CSS 以了解我的意思)。
现在,问题是:如何添加 20px 边距并确保所有 .item div 保持相同大小?我可以使用宽度的百分比并将删除的 .item 宽度添加为边距,但这永远不会是稳定的 20 像素,因为它是百分比。
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,而是使用padding。还要确保你在所有元素上使用box-sizing: border-box。 -
@RobScott 你能解释一下我为什么要添加
box-sizing吗?我以前从未见过。编辑:好的,盒子大小很聪明,谢谢,对将来的参考也很有用。在我的情况下,填充不是一种选择。 -
jsfiddle.net/3856h9e2这是你想要的结果吗?
-
@TusharGupta 是的,这正是我所需要的,谢谢!如果您将其添加为答案,我会接受。
-
@Rvervuurt
box-sizing使得当您定义width时,它会添加到帐户margin, padding, and borders中。没有它,你的宽度并不是你期望的那样