我有一个布局:一个容器有四列。只要我明确调整每列内的图像大小,它就可以正确格式化。我想指定图像宽度的百分比,以便布局灵活,但是当我这样做时,图像会扩展到主容器的宽度,而不是包含图像的列。
相关(我认为)位接近底部。
CSS Desk:http://www.cssdesk.com/Gb2Qd
HTML
<div id=maincontent>
<div id="shop-panels" class="flexcontainer">
<div class="panel" id="panel1">
<div class="content">
<img src="https://s24.postimg.org/dn7cdoifp/sedan.jpg"/>
</div>
<div class="caption">
Shop Sedans
</div>
</div>
<div class="panel " id="panel2">
<div class="content">
<img src="https://s1.postimg.org/ujt0z038v/truck.jpg" alt=""/>
</div>
<div class="caption">
Shop Trucks
</div>
</div>
<div class="panel " id="panel3">
<div class="content">
<img src="https://s24.postimg.org/w16ku1ymt/minivan.jpg" alt=""/>
</div>
<div class="caption">
Shop Minivans
</div>
</div>
<div class="panel " id="panel4">
<div class="content">
<img src="https://s22.postimg.org/6gw49w8gh/suv.jpg" alt=""/>
</div>
<div class="caption">
Shop SUVs
</div>
</div>
</div>
</div>
CSS
body {
font-family: 'Lucida Grande', 'Helvetica Neue', Helvetica, Arial, sans-serif;
font-size: 14px;
}
div#maincontent {
width: 980px;
background: #FFF;
height: 100%;
margin: auto;
padding: 1em;
box-sizing: border-box;
}
#shop-panels {
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
width: 100%;
}
#shop-panels div.panel {
-webkit-flex: 1 0 auto;
-ms-flex: 1 0 auto;
flex: 1 0 auto;
height: 200px;
border-radius: 1em;
margin: .5em;
padding: 1em;
background: #A00;
background: -webkit-linear-gradient(rgba(200,0,0,1),rgba(127,0,0,1));
background: -moz-linear-gradient(rgba(200,0,0,1),rgba(127,0,0,1));
background: linear-gradient(rgba(200,0,0,1),rgba(127,0,0,1));
}
#shop-panels div.panel:first-child {
margin-left: 0;
}
#shop-panels div.panel:last-child {
margin-right: 0;
}
#shop-panels div.panel:hover {
background: #C00;
}
#shop-panels div.panel .content {
background: #FFF;
border-radius: 1em;
height: 150px;
overflow: hidden;
text-align:center;
}
#shop-panels div.panel .content img {
position: relative;
/* THIS IS THE CULPRIT RIGHT HERE */
width: 100%;
/* IF THIS VALUE IS 190px, EVERYTHING'S FINE. */
top: 50%;
-webkit-transform: translateY(-50%);
-moz-transform: translateY(-50%);
-ms-transform: translateY(-50%);
transform: translateY(-50%);
}
#shop-panels div.panel > .caption {
color: white;
text-align: center;
font-weight: bold;
font-size: 1.5em;
margin: .7em 0;
text-shadow: 2px 2px 2px rgba(0,0,0,.8);
}
答案 0 :(得分:2)
#shop-panels div.panel {
flex: 0 1 25%;
}
#shop-panels div.panel .content img {
width: 100%;
}
为什么会这样:
flex: 1 0 auto;
...在您的代码中,表示:
flex-grow: 1;
flex-shrink: 0;
flex-basis: auto;
...显然 不 你想要什么。如果您不希望flex项目增长超过25%,则需要将其设置为:
flex: 0 1 25%;
或者,也可以将弹性项目max-width
设置为:
max-width: calc(25% - 1em); /* subtracting margins */
旁注:不要使用前缀CSS。仅使用干净的语法并在结尾处使用autoprefixer。为获得最大兼容性,请在其下方的框中设置> 0%
。
答案 1 :(得分:2)
将#shop-panels div.panel
的弹性值从1 0 auto
更改为1
,如下所示:
#shop-panels div.panel {
-webkit-flex: 1;
-ms-flex: 1;
flex: 1;
...
}
通过将flex-shrink
(第二个值)设置为0
,您不允许它们缩小