css 文本样式在其中的子元素之后中断

myss37ts  于 2023-07-01  发布在  其他
关注(0)|答案(3)|浏览(123)

我有一个简单的<p>元素,其中包含文本,并且在文本的中途我想插入一个图像。由于某些原因,图像后面的文本没有根据样式表进行样式化:

p {
  font-size: 20px;
}
<p>
  Text is styled according to the stylesheet.
  <div></div>
  Text loses its styling.
</p>

为什么会这样?

de90aj5v

de90aj5v1#

您的标记无效!使用标记验证器检查项目的编码是否有效。
问题是,段落(<p>)是一个单独的文本块容器,其中需要流文本。然而,div是一个块容器,因此与span不同,它不是流文本的容器。
现代主流浏览器具有自动更正功能,可以修复代码中的大多数错误,仍然呈现文档,而不会完全破坏自己。
您的代码将被浏览器更正,如下所示:

<p>
  Text is styled according to the stylesheet.
</p>
<div></div>
Text loses its styling.

这样你就会明白为什么第二行不再受CSS样式的影响。

解决方案

你在评论中说:
@ralph.m是的,那是因为我想在它下面添加对图像的描述。
这一点我必须说,div也不是一个合适的容器。正确的方法是使用figurefigcaption

<figure>
  <img src="https://via.placeholder.com/200.jpg">
  <figcaption>This is just a Placeholder Image</figcaption>
</figure>

然而,如上所述,在段落中包含流文本之外的任何内容都是不正确的。因此,您必须按如下方式拆分标记:

<p>Text is styled according to the stylesheet.</p>
<figure>
  <img src="https://via.placeholder.com/200.jpg">
  <figcaption>This is just a Placeholder Image</figcaption>
</figure>
<p>More flow-text.</p>
zz2j4svz

zz2j4svz2#

把它分成两个p标签就可以了。
这是因为
标签是用于表示文本段落的块级元素。它应该只包含内联元素,如text或其他内联元素,如span,a,strong等。

p {
  font-size: 20px;
}
<p>
  Text is styled according to the stylesheet.
</p>
  <div></div>
<p>
  Text does not lose its styling.
</p>

或者尝试使用span标记或任何内联元素

p {
  font-size: 20px;
}
<p>
  Text is styled according to the stylesheet.
  <span></span><br>
  Text does not lose its styling.
</p>
vuktfyat

vuktfyat3#

因为你定义了两个不同的块。
<p>元素是一个块级元素,应该只包含行内级元素,而不是像<div>这样的其他块级元素。定义类时,其设置将仅影响已定义的块级元素,而不影响其后的块。

<p>
  Text is styled according to the stylesheet.
  <!-- The <img> tag is the correct tag to use. -->
  <img src="your-image-url.jpg" alt="Your Image Description">
  Text retains its styling.
</p>

每个HTML标签都有自己的默认设置,以满足其目的。

相关问题