CSS 属性不适用于包含 pre 元素的段落

CSS properties don’t work for paragraphs with pre elements inside

我有一段包含 <pre> 元素和一些文本,如下所示:

<p class="par1">
     <pre>
           this is second paragraph
           ok
           ok
     </pre>
     These text are inside the paragraph must be RED
</p>

并且我用下面的代码改变了段落的背景颜色,但是没有影响到段落,不知道为什么。

<style>
     .par1{
           background-color:red;
           color:green;
     }
</style>

完整代码如下:

<!doctype html>
<html>

<head>
  <title>Test id and class attribute</title>
  <style>
    .par1 {
      background-color: red;
      color: green;
    }
  </style>
</head>

<body>
  <div class="div1">
    Some text
    <h1>An important heading</h1>
    <p class="par1">
      <pre>
          this is second paragraph
          ok
          ok
      </pre>
      This text is inside the paragraph and it must be red.
    </p>
  </div>
</body>

</html>

我知道如果我使用div .div1的class,它工作正常,但我想知道为什么第一个不起作用。

.div1{
    background-color:red;
    color:green;
}

根据 W3c specs say,您不能在 p

中包含 pre

4.4.1 The p element

Content model:

Phrasing content.

其中 Phrasing Content 是:

Phrasing content is the text of the document, as well as elements that mark up that text at the intra-paragraph level. Runs of phrasing content form paragraphs.

a abbr area (if it is a descendant of a map element) audio b bdi bdo br button canvas cite code data datalist del dfn em embed i iframe img input ins kbd keygen label map mark math meter noscript object output progress q ruby s samp script select small span strong sub sup svg template textarea time u var video wbr

您可以改用 span 并将其设置为 display:block,这将使它成为块级元素

.par1 {
  background-color: red;
  color: green;
  display: block
}
<div class="div1">
  Some text
  <h1>An important heading</h1>
  <span class="par1">
    <pre>
      this is second paragraph
       ok
       ok
    </pre>
    These text are inside the paragraph must be RED
  </span>
</div>

如@dippas 所说,它是关于 <p>-标签内的 <pre>-标签

<p>-标签不能包含块级元素。由于 <pre> 是块级元素,浏览器似乎会在 <pre> 标签打开之前关闭 <p> 标签(请参阅浏览器检查器)。因此 <p> 上的样式无法被 <pre>-tag

继承

有关带有有用提示的良好讨论,请参阅:

<pre> tag making browsers close paragraphs

编辑:

在 W3C 规范中,据说 "A paragraph is typically a run of phrasing content (...)"。

https://www.w3.org/TR/html5/dom.html#paragraphs