gpt4 book ai didi

CSS - 使段落文本环绕图像而不 float

转载 作者:技术小花猫 更新时间:2023-10-29 11:06:07 31 4
gpt4 key购买 nike

我可以简单地使用 float实现文字环绕 <img>元素,我明白 <img>是一个行内元素并且 <p>是一个 block 级元素,所以要使它们内联,我应该制作 <p>内联元素或使用 <span>相反。

问题是,如果我将它们全部视为内联元素,它会在图像旁边和文本顶部留下一个巨大的空白区域。

enter image description here

我想知道是什么导致了空白。

这是我的 JS Fiddle

最佳答案

这个问题似乎更关心为什么而不是如何,所以我将专注于内部工作:

Visual formatting model CSS 2.1 规范的部分描述了 inline formatting contexts :

In an inline formatting context, boxes are laid out horizontally, one after the other, beginning at the top of a containing block. Horizontal margins, borders, and padding are respected between these boxes. The boxes may be aligned vertically in different ways: their bottoms or tops may be aligned, or the baselines of text within them may be aligned. The rectangular area that contains the boxes that form a line is called a line box.

他们描述的属性是 vertical-align它采用许多不同的值,baseline作为默认值。这就是为什么你的两个 inline通过位于基线,元素按原样显示。您可以更改 <p>vertical-align: top , 并且第一行文本的顶部将与图像的顶部对齐。但是,您仍然会在第一行文本和后续行之间看到一个空隙。

这是因为文本将一个 line-box 垂直渲染到下一个。不管第一行的 line-box 是否比其余的大,它仍然会一次流一个 line-box。这是这个概念的可视化:

enter image description here

理解这一点的另一个重要概念是 <img>是一个replaced inline 元素,这意味着它的外观是由文档外部的外部资源构建的。 替换内联 元素可以采用 height值,而所谓的非替换内联(如 <span> )元素则不能。这就是为什么 <img> <span>foo</span>可以与 <span>foo</span> <em>bar</em> 不同(因为图像具有固有高度),即使它们都是行内元素。想象一下,将图像的高度设置为文本的 x 高度——它会有效地呈现与您的图像相同的效果,但在这种情况下,它的行为完全符合您的预期:

img {
height: 10px;
}

p {
display: inline;
}
<div>
<img src="http://placehold.it/100x100/E8117F/000.png">
<p>hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello</p>
</div>

这可能是一些困惑发生的地方。如果您能想象这些行,那么您就会明白,我们并不期望内联元素表现得像 float 元素。

将该信息与规范中关于 floats 的内容进行比较:

A float is a box that is shifted to the left or right on the current line. The most interesting characteristic of a float (or "floated" or "floating" box) is that content may flow along its side (or be prohibited from doing so by the 'clear' property). Content flows down the right side of a left-floated box and down the left side of a right-floated box.

A floated box is shifted to the left or right until its outer edge touches the containing block edge or the outer edge of another float. If there is a line box, the outer top of the floated box is aligned with the top of the current line box.

虽然我无法向您描述电子发生了什么,但我希望这是一个很好的起点,可以帮助您理解为什么这些不同的场景会呈现出它们的行为方式。

关于CSS - 使段落文本环绕图像而不 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20085418/

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