如何选择具有某个类的元素? [英] How do I select an element that has a certain class?

查看:138
本文介绍了如何选择具有某个类的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的理解是,使用 element.class 应该允许分配给类的特定元素接收不同于类的其余部分的样式。这不是一个问题,这是否应该使用,而是我试图理解这个选择器是如何工作的。从互联网上看一大堆例子,我相信语法是正确的,不明白为什么这不工作。

My understanding is that using element.class should allow for a specific element assigned to a class to receive different "styling" than the rest of the class. This is not a question about whether this should be used or not, but rather I'm trying to understand how this selector is intended to work. From looking at a ton of examples on the internet, I believe the syntax is correct and do not understand why this is not working.

以下是一个示例:

CSS:

h2 {
    color: red;
}

.myClass {
    color: green;
}

h2.myClass {
    color: blue;
}

HTML:

<h2>This header should be RED to match the h2 element selector</h2>
<div class="myClass">
    <h1>This header should be GREEN to match the class selector</h1>
    <h2>This header should be BLUE to match the element.class selector</h2>
</div>


推荐答案

应该是这样:

h2.myClass 用类 myClass 寻找h2。但是你实际上想要在 .myClass 中应用h2的样式,所以你可以使用后代选择器 .myClass h2 p>

h2.myClass looks for h2 with class myClass. But you actually want to apply style for h2 inside .myClass so you can use descendant selector .myClass h2.

h2 {
    color: red;
}

.myClass {
    color: green;
}

.myClass h2 {
    color: blue;
}



演示



参考将提供关于选择器的一些基本概念,并查看后代选择器

Demo

This ref will give you some basic idea about the selectors and have a look at descendant selectors

这篇关于如何选择具有某个类的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆