Html 如何为CSS类中的元素设置不同的头规则

Html 如何为CSS类中的元素设置不同的头规则,html,css,stylesheet,Html,Css,Stylesheet,好吧,这很难解释;因此,它也很难搜索,所以我只想在这里问一下 基本上,我有一个CSS类,我正在应用于某些div。在每个类中,我希望规则只适用于该DIV中的某些选择器 例如,假设我有这样一个CSS类 .main_wrapper { text-align: center; h1 { color: blue; } } .question_wrapper { text-align: left;

好吧,这很难解释;因此,它也很难搜索,所以我只想在这里问一下

基本上,我有一个CSS类,我正在应用于某些div。在每个类中,我希望规则只适用于该DIV中的某些选择器

例如,假设我有这样一个CSS类

  .main_wrapper {
        text-align: center;

        h1
    {
        color: blue;
    }

    }

    .question_wrapper  {
        text-align: left;

        h1
    {
        color: red;
    }
    }
<div class="main_wrapper">

    <h1>Test 1</h1>

    <div class="question_wrapper">

        <h1>Test 2</h1>

    </div>

</div>
然后让我们假设我有这样的HTML

  .main_wrapper {
        text-align: center;

        h1
    {
        color: blue;
    }

    }

    .question_wrapper  {
        text-align: left;

        h1
    {
        color: red;
    }
    }
<div class="main_wrapper">

    <h1>Test 1</h1>

    <div class="question_wrapper">

        <h1>Test 2</h1>

    </div>

</div>

测试1
测试2
我想用CSS实现的是将主包装div中的h1标记设为蓝色,而有问题的h1标记设为红色

我知道我这里的CSS不起作用,但这基本上就是我想要实现的

我希望这是有道理的

如果有人有什么好主意。

你必须使用以下方法:

.main_wrapper > h1{
   color:blue;
}

.question_wrapper > h1{
   color:red;
}
是指在

之前的直接子对象。您必须使用此选项:

.main_wrapper > h1{
   color:blue;
}

.question_wrapper > h1{
   color:red;
}

表示在

之前的what的直接子元素。您可以使用'>'运算符来选择子元素

.main_wrapper > h1 {
color: blue;
}

.question_wrapper > h1{
color:red;
}

可以使用“>”运算符选择子元素

.main_wrapper > h1 {
color: blue;
}

.question_wrapper > h1{
color:red;
}
如果这是你的SCS

 .main_wrapper {
        text-align: center;

        h1
    {
        color: blue;
    }

    }

    .question_wrapper  {
        text-align: left;

        h1
    {
        color: red;
    }
    }
这将是你的CSS

.main_wrapper {
  text-align: center;
}
.main_wrapper h1 {
  color: blue;
}

.question_wrapper {
  text-align: left;
}
.question_wrapper h1 {
  color: red;
}
…这会奏效的

如果这是您的SCS

 .main_wrapper {
        text-align: center;

        h1
    {
        color: blue;
    }

    }

    .question_wrapper  {
        text-align: left;

        h1
    {
        color: red;
    }
    }
这将是你的CSS

.main_wrapper {
  text-align: center;
}
.main_wrapper h1 {
  color: blue;
}

.question_wrapper {
  text-align: left;
}
.question_wrapper h1 {
  color: red;
}
…这会奏效的


那是CSS代码少/SASS吗?你应该避免在一个文档中有多个h1元素,很少有一个以上最重要的标题。@昆汀……虽然我理解你的意思,但现在已经不是了。@slister我不知道你为什么说它不起作用-这是CSS代码少/SASS吗?你应该避免在一个文档中有多个h1元素,很少有多个最重要的标题。@Quentin…不再是真的,尽管我理解你的意思。@slister我不知道你为什么说它不起作用-谢谢大家的快速和有用的回答。Stack Overflow社区的帮助让我惊讶不已。谢谢大家的快速和有用的回复。Stack Overflow社区的帮助让我感到惊讶。