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

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

问题描述

我的理解是,使用 element.class 应该允许分配给类的特定元素接收与类的其余部分不同的样式".这不是关于是否应该使用它的问题,而是我试图了解这个选择器是如何工作的.通过查看互联网上的大量示例,我相信语法是正确的,但不明白为什么这不起作用.

这是一个例子:

CSS:

h2 {红色;}.我的课 {颜色:绿色;}h2.myClass {颜色:蓝色;}

HTML:

<h2>这个标头应该是红色的以匹配 h2 元素选择器</h2><div class="myClass"><h1>这个头应该是绿色的以匹配类选择器</h1><h2>这个标头应该是蓝色的以匹配 element.class 选择器</h2>

解决方案

应该是这样的:

h2.myClass 寻找类 myClass 的 h2.但是您实际上想在 .myClass 中为 h2 应用样式,以便您可以使用后代选择器 .myClass h2.

h2 {红色;}.我的课 {颜色:绿色;}.myClass h2 {颜色:蓝色;}

演示

这个 ref 会给你一些关于选择器的基本概念,看看后代选择器

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.

Here is an example:

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>

解决方案

It should be this way:

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天全站免登陆