CSS更改样式而无需重写

时间:2019-04-10 17:29:42

标签: html css

当我有这个html文件时:

<html>
    <head>
        <style>
            h1{
                color: green;
            }
            main{
                color: red;
            }
        </style>
    </head>
    <body>
        <h1>I'm green!</h1>
        <main>
            <h2>I'm red!</h2>
            <h1>I also should be red!</h1>
        </main>
    </body>
</html>

我能不写第二个h1(在main内)main h1{color: red;}吗?

2 个答案:

答案 0 :(得分:2)

是的...

不过最好不要写main h1 { color: red } ...为什么不能这样做?

h1 {
  color: green;
}

h1:last-child {
  color: red;
}

main {
  color: red;
}

</style>
<h1>I'm green!</h1>
<main>
  <h2>I'm red!</h2>
  <h1>I also should be red!</h1>
</main>

答案 1 :(得分:2)

您可以为要更改样式的元素创建一个类或id:

h1 {
  color: green;
}

main{
  color: red;
}

.specific-h{
  color: red;
}

</style>
<h1>I'm green!</h1>
<main>
  <h2>I'm red!</h2>
  <h1 class="specific-h">I also should be red!</h1>
</main>

或者您也可以使用“ id”标签:

h1 {
  color: green;
}

main{
  color: red;
}

#specific-h{
  color: red;
}

</style>
<h1>I'm green!</h1>
<main>
  <h2>I'm red!</h2>
  <h1 id="specific-h">I also should be red!</h1>
</main>