容器是1200px,每个div只有292px宽。理想情况下,div 1位于左边,div 3位于右边,div 2位于它们中间。更复杂的是,当在移动设备上查看时,容器将减少到320px,并且所有3个div都应该垂直排列,在彼此下方。目前,每个div的css如下所示:
.test1 {
float:left;
width:292px;
background-color:#F2F2F2;
margin:0 4px 5px;
border:1px solid grey;
line-height:0;
}
在容器上使用text-align:justify
,这样无论容器中有多少元素,它都能工作(不必为每个列表项计算%宽度
FIDDLE
<div class="container">
<div class="test1"></div>
<div class="test1"></div>
<div class="test1"></div>
</div>
CSS
.container {
width: 1200px;
text-align: justify;
}
.container:after {
content: '';
display: inline-block;
width: 100%;
}
.container .test1{
display: inline-block;
width:292px;
background-color:#F2F2F2;
margin:0 4px 5px;
border:1px solid grey;
}
根据您的html结构,可以通过不同的方式实现您想要的内容。
使用float
:
<tag left :floatleft />
<tag right :float:right/>
<tag center :margin:auto/>
使用display:flex;
<parent
style="display:flex;justify-content:space-between;">
<child left />
<child center />
<child right />
</parent>
使用@media
查询,当宽度不足以容纳其中的3个时,可以将行布局切换为列布局:DEMO
section {
display:flex;
justify-content:space-between;
}
article {
width:292px;
background:green;
}
@media all and (max-width:900px) {
section {
flex-direction:column ;
}
article {width:100%;
}
}
<section>
<article> 292px width</article>
<article> 292px width</article>
<article> 292px width</article>
</section>
使用display:inline-block
:
<parent
style="text-align:center">
<child left style="display:inline-block"/>
<child center style="display:inline-block"/>
<child right style="display:inline-block"/>
<pseudo-tag style="display:inline-block;width:100%"/><!--this can be either a pseudo element or a neutral tag in HTML to enhance compatibility for IEs<8 -->
</parent>
这里有一个代码笔,可以轻松设置和调整3个框292px宽:http://codepen.io/gc-nomade/pen/nrbDl
你想要这样的东西吗?
.container {
width: 1200px;
}
.test1 {
float:left;
width: 24.333333333%;
height: 200px;
background-color:#F2F2F2;
margin-left:13.3%;
border:1px solid grey;
line-height:0;
}
.test1:first-child {
margin-left: 0;
}
jsfiddle