问题
I have the following setup, but setting the width of the divs to a something around 30% is not working consistently (once the window width goes less than some number the third divs drops below..
Is there a better way of doing this, so that my divs always stay inline and keep getting smaller and smaller while the margin stays fixed at 18px between them ?
CSS :
.parent {
width: 100%;
height: 50px;
}
.child {
float: left;
margin-right: 18px;
border: 2px solid white;
text-align: center;
line-height: 50px;
height: 100%;
width: ~30%; /* doesn't work */
}
.child:nth-child(3) {
margin-right: 0;
}
HTML :
<div class="parent">
<div class="child">one</div>
<div class="child">two</div>
<div class="child">three</div>
</div>
回答1:
If you are looking for IE8 support, and can change your markup, you can nest the blocks inside 33.33% width elements.
For IE8 support, you need to get rid of the nth-child() declaration. In order to have inner gaps only, I used the technique described here : Items grid with inner padding only.
DEMO
body{
overflow:hidden;
margin:0;
}
.wrap{
margin: 0 -9px;
}
.box {
width:33.33%;
float:left;
}
.box div {
background:grey;
height:150px;
margin:0 9px;
}
<div class="wrap">
<div class="box">
<div>one</div>
</div>
<div class="box">
<div>two</div>
</div>
<div class="box">
<div>three</div>
</div>
</div>
回答2:
Use calc()
to calculate column width.
.child {width: calc(33.333% - 12px);} /* margins in total have 36px / 3 cols */
Calc
is supported since IE9.
来源:https://stackoverflow.com/questions/27375820/3-fluid-divs-width-2-fixed-margins-between-them