将图像设置为在flex列中始终为全高

时间:2016-06-06 21:19:46

标签: html css css3 flexbox

我有两列设置为50%,左边是文本,右边是图像,应该垂直填充整列。问题是,当文字稍大时,图像下方会有一个间隙。是否可以始终使图像占据整个高度(但以相同的比例)?例如,图像可能比其列宽,在这种情况下,我可以设置隐藏溢出。



.flex {
  display: flex;
  border: 3px solid black;
  padding: 10px;
}

.col {
  border: 1px dashed #aaa;
}

.left {
  padding: 30px;
}

<div class="flex">
  <div class="col left">
    <p>
      Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestias eos fugiat deserunt ullam tempore? Aspernatur eligendi dolores explicabo officiis adipisci, incidunt distinctio tempore culpa, esse cumque atque repellendus eius delectus fugit quia odit
      ut porro laborum alias. Aliquam et est neque ut, rem ab omnis? Culpa rerum, vel ad magnam iusto explicabo at consequatur deserunt quo repellendus. Sequi nulla nemo a magni voluptates. Nemo mollitia, ut ex temporibus voluptatem incidunt nostrum quo,
      quod reprehenderit omnis! Sequi nulla nemo a magni voluptates.
    </p>
  </div>
  <div class="col right">
    <img src="http://placehold.it/550x250" alt="">
  </div>
</div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

您必须将以下CSS属性设置为图像

SELECT U1.id, U2.id, SUM(GCol) FROM users U1 JOIN users U2 ON U1.id <> U2.id LEFT JOIN (SELECT A.user_id AS A_id, B.user_id as B_id, (A.id IS NOT NULL) AS GCol FROM game_users_A A JOIN game_users_B B ON A.game_id = B.game_id AND A.user_id <> B.user_id) G ON U1.id = G.A_id AND U2.id = G.B_id GROUP BY GCol, U1.id, U2.id ORDER BY U1.id, U2.id

height:100%;
width:auto;
.flex {
  display: flex;
  border: 3px solid black;
  padding: 10px;
}
.col {
  border: 1px dashed #aaa;
  overflow-x: hidden;
}
.left {
  padding: 30px;
}
.right img {
  height: 100%;
  width: auto;
}

答案 1 :(得分:1)

使图像填充容器的垂直高度的最快方法是使父级成为弹性容器。这会自动将align-items: stretch应用于子项(在本例中为图像)。

.right { display: flex; }

从那时起,您可以使用各种方法为图像设置正确的宽高比。如果您已在父/祖先上定义了高度,则可以使用百分比高度。

或者您可以使用object-fit属性。

&#13;
&#13;
.flex {
  display: flex;
  border: 3px solid black;
  padding: 10px;
}
.col {
  border: 1px dashed #aaa;
}
.left {
  padding: 30px;
}
.right {
  display: flex;
}
img {
  object-fit: cover;
}
&#13;
<div class="flex">
  <div class="col left">
    <p>
      Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestias eos fugiat deserunt ullam tempore? Aspernatur eligendi dolores explicabo officiis adipisci, incidunt distinctio tempore culpa, esse cumque atque repellendus eius delectus fugit quia odit
      ut porro laborum alias. Aliquam et est neque ut, rem ab omnis? Culpa rerum, vel ad magnam iusto explicabo at consequatur deserunt quo repellendus. Sequi nulla nemo a magni voluptates. Nemo mollitia, ut ex temporibus voluptatem incidunt nostrum quo,
      quod reprehenderit omnis! Sequi nulla nemo a magni voluptates.
    </p>
  </div>
  <div class="col right">
    <img src="http://placehold.it/550x250" alt="">
  </div>
</div>
&#13;
&#13;
&#13;

请注意,Internet Explorer中本身不支持object-fit。有关详细信息和解决方法,请参阅:Why isn't object-fit working in flexbox?