浮动图像左,适合父,保持纵横比

use*_*106 5 html css css3

我有以下内容:jsfiddle.net

我想要做的是让图像浮动文本,使其填充父(.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;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

Mic*_*ger 0

据我所知,没有唯一的 HTML/CSS 解决方案可以完成这项工作 - 如果我错了,请纠正我。OP 希望将未知大小的图像动态缩放到父容器的高度。另一方面,该容器动态地取决于文本长度并且没有固定的高度。图像大小可能会有所不同,文本大小可能会有所不同。

这里是使用 jQuery 的概念验证<img>解决方案,而不是background-image以下结果: 图像缩放到框 HTML:

<div class="box">
  <img class="img" data-src='https://placehold.it/500x500'>
  <div class="text">This box is one line.</div>
</div>
Run Code Online (Sandbox Code Playgroud)

JavaScript / jQuery

var $boxes = $('.box');
var $imgs = $boxes.find('.img');
for (var i = 0; i < $boxes.length; i++) {
  var heightParent = $boxes.eq(i).outerHeight() - 4; 
  // -4 because of border 2px top + 2px bottom
  $imgs.eq(i).attr('src', $imgs.eq(i).attr('data-src'));
  $imgs.eq(i).height(heightParent);
}
Run Code Online (Sandbox Code Playgroud)

CSS(仅更改部分):

.img {
  float:left;
  margin-left: -24px;
  margin-top: -24px;
  margin-right: 10px;
}
Run Code Online (Sandbox Code Playgroud)

实现你想要的并不是一件小事,因为你不想设置高度。不在图像上,也不在父容器上。

使用背景图像的问题: 通过这种background-image方法,可以很容易地将图像正确缩放到左侧position:absolute,但右侧的边距(文本)不起作用,因为宽度可能不同。

使用 img 的问题: 另一方面,使用img 时<img>会遇到问题,<div>只要没有父级具有固定高度,父级将始终处于图像的原始高度 - 这就是您的示例中的情况。

JavaScript 使其部分正常工作: 为了避免这种情况,您可以通过将 url 设置为属性来避免在页面加载时创建图像data,我将其称为data-src. 现在,当页面加载时,您可以查找父级的<div> 自然高度。接下来,将 URL 从data-src属性传递到src属性,以便呈现图像。由于我们知道前父母的身高,我们可以将其设置为图像高度。

CSS 负边距用于撤消padding: 24px父容器上的设置,以便图像正确定位。如果您问自己为什么要从高度中减去 4,这是因为您希望图像位于边框,因此我们需要减去边框顶部的 2px + 底部的 2px。

注意:当然,如果没有进一步的脚本编写,这个解决方案将无法响应,但你的父母<div>似乎无论如何都没有响应。

小提琴: https: //jsfiddle.net/av9pk5kv/

布局愿望和上面的例子的问题: 您可能会说,想要的布局一开始就不值得追求,如果您不更改其他内容,它就无法处理更多的文本在某些时候,文本太多,因此不可能将图像填充到父级中: 两条多行的问题 为了部分避免这种情况,您必须删除父级的固定宽度。但是,如果通过 JavaScript 动态包含图像导致像以前一样产生更多文本行(文本被挤压),则会发生相同(或类似)的结果。

我将如何解决这些问题:我会使用另一种布局。