gpt4 book ai didi

html - 如何 float :left a container with an image having a relative width?

转载 作者:太空狗 更新时间:2023-10-29 12:24:59 26 4
gpt4 key购买 nike

我试图将宽度相对于页面宽度的图像左对齐。有几个我无法更改的不幸限制:

  • 图像有一个包装器,
  • 无法将宽度应用于包装器,因为负责宽度的类已应用于图像(而且我也无法更改它 :D),
  • 解决方案必须是纯 CSS。

结构如下:

<p>Lipsum...</p>

<div class="align-left">
<img src="http://lorempixel.com/1000/1000/" class="width50" alt="lipsum" width="1000" height="1000">
</div>

<p>Lipsum...</p>

CSS:

.align-left {
float: left;
background: red;
padding: 10px;
}

.width50 {
width: 50%;
height: auto;
}

参见:http://jsfiddle.net/xnt27crz/2/

问题:div.align-left 的样式是否可以不占用 100% 的宽度?它的宽度应该等于图像的宽度 + 它自己的填充。

更多事实:

  • 我得到的最接近的是 float 图像,而不是 div(因此它的高度为 0px),但这很糟糕并且导致了其他问题。
  • 我认为这可以通过 flexbox 实现,但我正在寻找 IE9+ 支持。
  • 我正在寻找一个“安全”的解决方案,因为许多开发人员随后会在我无法预测的许多场景中使用它。
  • 编辑:实际情况要复杂得多,因此存在限制。您可以在此处查看示例:http://jsfiddle.net/n1kayb2o/3/ .请注意,编辑器内部的结构与输入的 HTML 不同。还有一个额外的包装器,可以将图形和它具有的拖动 handle 以及可能需要的其他一些元素(例如叠加层)粘合在一起。

最佳答案

棘手的问题。我必须阅读规范才能帮助您解决问题,这是我的结果。

不可能用给定的约束来解决问题,因为这完全取决于图像的宽度(也称为“替换元素”)

为什么?

让我们阅读规范 http://www.w3.org/TR/CSS2/visudet.html#float-width

If 'margin-left', or 'margin-right' are computed as 'auto', their used value is '0'.

If 'width' is computed as 'auto', the used value is the "shrink-to-fit" width.

Calculation of the shrink-to-fit width is similar to calculating the width of a table cell using the automatic table layout algorithm. Roughly: calculate the preferred width by formatting the content without breaking lines other than where explicit line breaks occur, and also calculate the preferred minimum width, e.g., by trying all possible line breaks. CSS 2.1 does not define the exact algorithm. Thirdly, find the available width: in this case, this is the width of the containing block minus the used values of 'margin-left', 'border-left-width', 'padding-left', 'padding-right', 'border-right-width', 'margin-right', and the widths of any relevant scroll bars.

Then the shrink-to-fit width is: min(max(preferred minimum width, available width), preferred width).

让我们为您的案例做“数学”

Preferred minimum width = 1000px (real width of the image)
Available width = assume 1990 (roughly page width)
Preferred width = 1000px (real width of the image)

min(max(1000, 1990), 1000) = 1000

作为证明http://jsfiddle.net/xnt27crz/5/带有 200px 图像

总结

在您的情况下, float div 的宽度将等于图像的实际宽度。

关于html - 如何 float :left a container with an image having a relative width?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29704019/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com