【问题标题】:CSS properties don’t work for paragraphs with pre elements insideCSS 属性不适用于包含 pre 元素的段落
【发布时间】:2016-07-08 11:01:44
【问题描述】:

我有一个包含<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 的类,它可以正常工作,但我想知道为什么第一个不起作用。

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

【问题讨论】:

    标签: html css css-selectors pre


    【解决方案1】:

    根据W3c specs say,您不能在p 中包含pre

    4.4.1 p 元素

    内容模型:

    措辞内容。

    Phrasing Content 在哪里:

    短语内容是文档的文本,以及包含 在段落内标记该文本。语句的运行 内容形式的段落。

    a abbr area(如果它是 map 元素的后代) 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>

    【讨论】:

      【解决方案2】:

      正如@dippas 所说,这是关于&lt;p&gt;-tag 中的&lt;pre&gt;-tag

      &lt;p&gt;-tags 不能包含块级元素。由于&lt;pre&gt; 是块级元素,浏览器似乎在&lt;pre&gt;-标签打开之前关闭了&lt;p&gt;-标签(请参阅您的浏览器检查器)。因此&lt;p&gt; 上的样式不能被&lt;pre&gt;-tag 继承

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

      <pre> tag making browsers close paragraphs

      编辑:

      在 W3C 规范中,据说“一个段落通常是一系列措辞内容 (...)”。

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

      【讨论】:

      • 我们可以说“一个块级元素不能包含另一个块级元素”吗?
      • 不,不是。
        s 包含
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-09
      • 1970-01-01
      • 1970-01-01
      • 2015-07-08
      • 1970-01-01
      相关资源
      最近更新 更多