设置弹性行高度以适合子img大小

时间:2018-06-17 15:06:00

标签: html css css3 flexbox

我正在尝试制作一个flexbox行,以便将它的高度与子img相匹配,其高度由其宽度(来自CSS)和它的比例(来自文件)设置。 是否有纯CSS方式来实现这种行为?

.row {
  width: 50%; 
  height: auto; /* does not work */
  display: flex;
  flex-direction: row;
}

.row, .row > * {
  background: rgba(200, 0, 0, 0.1);
}

.row > .text {
  white-space: normal;
  flex-grow: 2; /* width: 100%  also works */
}

.row > img:last-child {
  width: 40%;
  height: auto;
  border: 0px;
}
<div class="row">
  <div class="text">Some text content, occupies all available space.<br/>Image to the right should have 4x3 ratio</div>
  <img src="https://www.christart.com/IMAGES-art9ab/clipart/5233/blown-leaves-background.jpg"><!-- a random 4x3 image from Internet -->
</div>

1 个答案:

答案 0 :(得分:1)

您只需更改the alignment,因为默认情况下stretch

&#13;
&#13;
.row {
  width: 50%; 
  display: flex;
  align-items:flex-start; /*added this*/
  flex-direction: row;
}

.row, .row > * {
  background: rgba(200, 0, 0, 0.1);
}

.row > .text {
  white-space: normal;
  flex-grow: 2; /* width: 100%  also works */
}

.row > img:last-child {
  width: 40%;
  border: 0px;
}
&#13;
<div class="row">
  <div class="text">Some text content, occupies all available space.<br/>Image to the right should have 4x3 ratio</div>
  <img src="https://www.christart.com/IMAGES-art9ab/clipart/5233/blown-leaves-background.jpg"><!-- a random 4x3 image from Internet -->
</div>
&#13;
&#13;
&#13;