使弹性项目使用弹性方向为父级的100%高度:行

时间:2018-09-12 17:25:08

标签: html css css3 flexbox

因此,我尝试在一个伸缩容器中放置3个高度和宽度相等的伸缩项目。我成功地使3个flex项目的宽度相等。但是,第一个flex-item具有一个div(.images),它也是一个flex容器,与其他2个flex项目的(.images)div相比,它包含更多的子代。这将导致第一个伸缩项目的高度大于其他两个伸缩项目的高度。如何使其他两个伸缩项目的高度与第一个伸缩项目的高度相同,即使子对象的数量不相同?我研究了此问题,但只有在flex-direction属性设置为column时才找到答案。在我的情况下,flex-direction属性在flex容器内设置为row。

body {margin: 0}

.flex-container {
  display: flex;
  flex-direction: row;
  width: 100%;
}

.flex-items {
  width: 33.333%;
  height: 100%;
}

.images {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  height: 100%;
  justify-content: center;
}
<div class="flex-container">
  <div class="flex-items">
    <h1>Some Title</h1>
    <div class="images">
      <img src="image1.jpg" alt="">
      <img src="image2.jpg" alt="">
      <img src="image3.jpg" alt="">
      <img src="image4.jpg" alt="">
      <img src="image5.jpg" alt="">
    </div>
  </div>
  <div class="flex-items">
    <h1>Some Title</h1>
    <div class="images">
      <img src="image6.jpg" alt="">
      <img src="image7.jpg" alt="">
    </div>
  </div>
  <div class="flex-items">
    <h1>Some Title</h1>
    <div class="images">
      <img src="image8.jpg" alt="">
      <img src="image9.jpg" alt="">
    </div>
  </div>
</div>

2 个答案:

答案 0 :(得分:0)

如果要按比例缩放图像,则需要将.images内的图像设置为100%的高度和自动的宽度,例如:

.images {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    height: 100%; (images is getting 100% height, but nothing is telling its children to go up in height)
    justify-content: center;
}

.images img { (address the children)
  height:100%;
  width:auto;
}

答案 1 :(得分:0)

如果您未设置图像的宽度和高度,它们将使用自动,并根据您所使用的浏览器自动将其缩放到伸缩框。

可以通过使用height或width属性对图像进行内联处理或使用CSS,以下两者都是一个示例。

内联示例1:

<img src="#.png" width="auto" height="100%" />

Css示例2:

div.images > img {  
 height: 100%;  
 width: auto;  
}   

最好为您的网页优化图像,而不要依靠自动缩放以获得最佳结果。毕竟,您是知道最终结果应该是什么的人。

:)