【问题标题】:Scope <style> only to that specific div范围 <style> 仅适用于该特定 div
【发布时间】:2022-02-14 18:34:00
【问题描述】:

我怎样才能将&lt;style&gt; 封装在&lt;div&gt; 中只封装到&lt;div&gt;

&lt;div class="test"&gt; 中的内容将来自带有预定义 &lt;style&gt; 和其他元素的数据库,因此我无法向元素添加类并根据它们的类设置这些元素的样式

第一个标题的颜色应该是绿色,而第二个标题的颜色应该是红色

<!DOCTYPE html>
<html>
    <head>
        <title>Title</title>
        <style>
            h1 {
                color: green;
            }
        </style>
    </head>

    <body>
        <h1>This is a heading</h1>

        <div class="test">
            <style>
                h1 {
                    color: red;
                }
            </style>
            
            <h1>This is a heading inside div.test</h1>
        </div>
    </body>
</html>

【问题讨论】:

  • 请注意,在 head 元素之外的 &lt;style&gt; 是无效的 HTML 标记。 Mozilla 终于在 2019 年弃用了 scope 属性,而 Chrome 已经在 2014 年弃用了它。

标签: html css css-selectors


【解决方案1】:

只需使用包含父元素类的组合选择器:

h1 {
  color: purple;
}
.test1 h1 {
  color: red;
}
.test2 h1 {
  color: green;
}
<h1>This is a heading</h1>

<div class="test1">
  <h1>This is a heading inside div .test1</h1>
</div>

<div class="test2">
  <h1>This is a heading inside div .test2</h1>
</div>

【讨论】:

    【解决方案2】:

    您可以做的是给每个 h1 特定的样式名称。因此,对于您的第一个标题,它将是:

    h1-1 {
       color: red;
    }
    

    但是,这样做效率很低,也不是很专业。这是最干净的处理方式:

    .test h1 {
        color: red;
    }
    

    您正在做的是选择带有.test 的父类,然后选择子类并将红色应用于它。

    这是一个代码 sn-p 来展示它是如何工作的。

    .parent .child {
      color: red;
     }
    <h1>This block is uncolored!</h1>
    
    <div class="parent">
      <h1 class="child">
        This is colored red!
      </h1>
    </div>

    【讨论】:

      【解决方案3】:

      我会这样做:DB 中的每个用户内容都有一个 ID 元素,用于包装其内容,然后必须包含在内。这样你就可以封装任何样式:

      h1 {
        color: green;
      }
      <h1>This is a heading</h1>
      
      <!-- random generated ID wrapper -->
      <div id="wrapper-00123ABCFF">
        <div class="test">
          <style>
            #wrapper-00123ABCFF h1 {
              color: red;
            }
          </style>
      
          <h1>This is a heading inside div.test</h1>
        </div>
      </div>
      <div id="wrapper-AFFCC0023">
        <div class="test">
          <style>
            #wrapper-AFFCC0023 h1 {
              color: yellow;
            }
          </style>
      
          <h1>This is a heading inside div.test</h1>
        </div>
      </div>

      如果使用 CssLess 生成样式会更加容易:

      #wrapper-AFFCC0023 {
         /* ... User style */
      }
      

      否则你应该使用一些正则表达式来为任何顶级选择器添加前缀

      【讨论】:

        猜你喜欢
        • 2021-04-23
        • 2014-03-08
        • 1970-01-01
        • 1970-01-01
        • 2021-03-07
        • 1970-01-01
        • 2015-12-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多