有没有一种方法可以使 类属性应用于不同的元素?

问题描述 投票:0回答:2

我想知道是否有一种方法可以使用div标签为同一类的不同元素设置样式。我知道这可行:

<head>
<style>
.intro { color: red }
</style>
</head>

<body><div class="intro">

<p>This should be red.</p>

</div></body>

而且这也有效:

<head>
<style>

h1.intro { color: blue }
p.intro { color: red }

</style>
</head>
<body>

<h1 class="intro">This should be blue.</h1>
<p class="intro">This should be red.</p>

</body>

因此,鉴于此,您会认为类似的事情会起作用:

<head>
<style>

h1.intro { color: blue }
p.intro { color: red }

</style>
</head>
<body>

<div class="intro">

<h1>This should be blue.</h1>
<p>This should be red.</p>

</div>

</body>

但是没有运气。有没有办法做到这一点?还是我应该放弃并输入很长的路要走?任何帮助将不胜感激。

html css class
2个回答
0
投票

您必须使用

.intro h1 { color: blue }
.intro p { color: red }

,因为h1p元素是.intro div的子级

或者您可以在元素本身上使用类:

.intro1 { color: blue }
.intro2 { color: red }
<div>

<h1 class="intro1" >This should be blue.</h1>
<p class="intro2" >This should be red.</p>

</div>

0
投票

这将使您的示例工作:

<html>
    <head>
    <style>

    .intro h1 { color: blue }
    .intro p { color: red }

    </style>
    </head>
    <body>

    <div class="intro">

    <h1>This should be blue.</h1>
    <p>This should be red.</p>

    </div>

    </body>

</html>

使用“ .intro”标识容器,然后指定内部元素样式。

© www.soinside.com 2019 - 2024. All rights reserved.