背景故事:以下基于flexbox
的布局按预期工作。当我缩小浏览器的宽度时,所有三个图像均以相同的比例缩小。如果您运行代码段,请单击Full page
链接并缩放浏览器以查看此简单效果。
.flexParent {
display: flex;
margin: 0 auto;
width: 80%;
}
.flexChildOne {
margin-right: 16px;
}
.flexChildOne img {
width: 100%;
height: auto;
}
.flexInterior {
display: flex;
overflow: hidden;
}
.flexChildTwo {
width: 400px;
margin-right: 16px;
}
.flexChildTwo img {
width: 100%;
height: auto;
}
.flexChildThree {
width: 400px;
}
.flexChildThree img {
width: 100%;
height: auto;
}
<div class="flexParent">
<div class="flexChildOne"><img src="https://i.stack.imgur.com/9lzSH.jpg"></div>
<div class="flexInterior">
<div class="flexChildTwo"><img src="https://i.stack.imgur.com/8Q4Q7.jpg"></div>
<div class="flexChildThree"><img src="https://i.stack.imgur.com/5vBC6.jpg"></div>
</div>
</div>
但是,当我将flex-direction: column;
添加到flexInterior
类时,效果无法按需工作。左侧图像按比例缩放,但flexInterior
中的两个图像保持静态。随着浏览器缩小而不是缩放,它们的右边缘逐渐被切断。这是因为在原始行布局中需要行overflow: hidden;
以引起缩放效果,但是在列布局版本中会产生此新的剪切问题。
问题:在列布局中,如何使图像缩放与行布局类似?这是一个简化的示例。在实际版本中,我使用媒体查询来显示列或行版本,具体取决于浏览器的宽度。
.flexParent {
display: flex;
margin: 0 auto;
width: 80%;
}
.flexChildOne {
margin-right: 16px;
}
.flexChildOne img {
width: 100%;
height: auto;
}
.flexInterior {
display: flex;
flex-direction: column; /* Only line that was changed */
overflow: hidden;
}
.flexChildTwo {
width: 400px;
margin-right: 16px;
}
.flexChildTwo img {
width: 100%;
height: auto;
}
.flexChildThree {
width: 400px;
}
.flexChildThree img {
width: 100%;
height: auto;
}
<div class="flexParent">
<div class="flexChildOne"><img src="https://i.stack.imgur.com/9lzSH.jpg"></div>
<div class="flexInterior">
<div class="flexChildTwo"><img src="https://i.stack.imgur.com/8Q4Q7.jpg"></div>
<div class="flexChildThree"><img src="https://i.stack.imgur.com/5vBC6.jpg"></div>
</div>
</div>
答案 0 :(得分:2)
.flexInterior
的子元素比其父元素宽
从.flexChildTwo
和.flexChildThree
删除宽度,并将其添加到.flexInterior
.flexInterior {
display: flex;
flex-direction: column;
overflow: hidden;
width: 400px
}
示例:https://codepen.io/IanJohnson/pen/QzqggE?editors=1100
您还希望摆脱margin-right
在列布局中的作用