html - 向左浮动图像,适合父级,保持纵横比

标签 html css

我有以下内容:jsfiddle.net

我想要做的是让图像 float 在文本的左侧,以便它填充父级 (.box)。请注意,.box 的高度可能因文本行数而异。

最终结果应如下所示:i.imgur.com

这将如何完成?

.box {
  position: relative;
  display: block;
  width: 600px;
  padding: 24px;
  margin-bottom: 24px;
  border: 2px solid red;
}
.img {
  float: left;
}
.text {
  font-size: 14px;
}
<div class="box">
  <div class="img" style="background-image: url('https://pixabay.com/static/uploads/photo/2015/10/01/21/39/background-image-967820_960_720.jpg');"></div>
  <div class="text">This box is one line.</div>
</div>

<div class="box">
  <div class="img" style="background-image: url('https://pixabay.com/static/uploads/photo/2015/10/01/21/39/background-image-967820_960_720.jpg');"></div>
  <div class="text">This box has two lines. This box has two lines. This box has two lines. This box has two lines. This box has two lines. This box has two lines.</div>
</div>

最佳答案

您可以在父元素上使用display: table,在子元素上使用display: table-cell

PLUNKER

片段

<!DOCTYPE html>
<html>

<head>
  <style>
    html,
    body {
      height: 100%;
      width: 100%;
    }
    figure {
      display: table;
      width: 600px;
      height: auto;
      margin-bottom: 24px;
      border: 2px solid red;
    }
    img {
      float: left;
      display: table-cell;
      min-height: 100%;
      margin-right: 20px;
    }
    figcaption {
      font-size: 14px;
      height: 100%;
    }
  </style>
</head>

<body>
  <figure>
    <img src="http://i.imgur.com/MhHgEb1.png">
    <figcaption>This box is one line.</figcaption>
  </figure>

  <figure>
    <img src="http://i.imgur.com/MhHgEb1.png">
    <figcaption>This box has two lines. This box has two lines. This box has two lines. This box has two lines. This box has two lines. This box has two lines.</figcaption>
  </figure>
</body>

</html>

关于html - 向左浮动图像,适合父级,保持纵横比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39477885/

相关文章:

html - DIV适合父级的宽度内容

html - 如何在 html 中使用文本自动空格声明

javascript - HTML//CSS//JavaScript : button or input doesn't show up on web

php - load() 函数添加的内容在 ajax 操作后消失

javascript - 在具有仪表板和登陆的 React 应用程序中处理 CSS 样式冲突的最佳方法是什么?

javascript - 使用 getComputedStyle().getPropertyValue() 获取边框值? (莫斯拉,FF)

html - Cufon 始终呈现为粗体

html - CSS如何垂直居中对齐菜单的div float 元素?

javascript - 表单验证空字段在 Angular 2+ 中显示为无效

css - 如何使具有不同 anchor 元素的div的整个背景颜色可点击