【问题标题】:Apply css stylesheet to specific div将 css 样式表应用于特定的 div
【发布时间】:2020-02-12 14:40:42
【问题描述】:

我正在尝试为 div 应用特定的样式表,我不想为此使用 iframe,我试过这个:

<div id="superdiv">

  <style>
    #superdiv {
      @import url("./css/style.css");
    }
  </style>


//html that apply css here from stylesheet linked before
<h1 class="x"> Hello</h1>

</div>

【问题讨论】:

标签: html css


【解决方案1】:

如果您想设置 &lt;div&gt; 的子元素的样式,例如&lt;h1&gt; 标题独立于容器外部的其他可能的 &lt;h1&gt; 元素,您只能使用单个 CSS 文件来执行此操作。

CSS 提供了强大的 > 选择器,让您可以为子元素设置规则。

在您的情况下,容器 &lt;div&gt; 的 ID 为 superdiv,可通过以下方式访问:

#superdiv
{
}

要访问子元素 - 在您的情况下是 &lt;h1&gt; 标签 - 只需:

#superdiv > h1
{

}

这是一个例子:

h1 {
  color: #00ff00;
}

#superdiv {
  background-color: #efefef;
  border: 1px solid #ff0000;
}

#superdiv>h1 {
  color: #0000ff;
}
<h1>Hello</h1>
<div id="superdiv">
  My content
  <h1>Hello</h1>
</div>

【讨论】:

    【解决方案2】:

    您不会在 div 中创建特定的样式表 试试这个方法

    <div id="style-sheet-modern"> 
       <div class="my-class"></div>
       <div class="etc"></div>
    </div>
    
    #style-sheet-superdiv .my-class{
        color:black;
    } 
    
    #style-sheet-modern .etc {
       color:red;
    }
    

    【讨论】:

      猜你喜欢
      • 2018-11-30
      • 2014-05-01
      • 2015-12-26
      • 1970-01-01
      • 2013-04-12
      • 2012-06-27
      • 1970-01-01
      • 1970-01-01
      • 2011-09-26
      相关资源
      最近更新 更多