html - 设置 flex 行高以适合子 img 大小

标签 html css 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>

最佳答案

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

.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;
}
<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>

关于html - 设置 flex 行高以适合子 img 大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50897878/

相关文章:

javascript - 浮起来的行

java - 在 jsoup 选择器中使用逻辑或、非和

css - 如何在 div/图像上添加透明到黑色的渐变?

html - 不同的柔性容器并排

javascript - 当用户单击 Enter 按钮时触发按钮

html - 背景不透明度

CSS3 文本动画在重新启动时过快地重叠 First-child

javascript - jCarousel + jQuery Accordion + fadeIn

html - Flexbox 布局中的等高图像

html - 如何设置与主要内容重叠的粘性页脚背景?