简体   繁体   English

仅在特定元素内引用CSS类

[英]Referencing a CSS class only within a specific element only

I have defined this: 我已经定义了:

.grade a{
    color: white;
}

It works. 有用。 too well.. 太好..

I have an html like so 我有一个像这样的html

<li class="grade">
   <a><i class="fa fa-star fa-fw"></i></a>
      My Text 
</li>

The bootsrap i star element is painted white. bootsrap i star元素被漆成白色。 And I don't want it to. 而且我不想要它。

How can I only specify element with a of class .grade 我怎样才能只指定.class类的元素

<a class="grade"> Text here should be white </a>

and not other elements? 而不是其他元素?

As is, you are selecting any a element which is a descendant of an element with the class grade . 正如,你选择的任何a元素是与类元素的后代grade

To specify an a element that has the grade class itself, change your selector to: 要指定本身具有gradea元素,请将选择器更改为:

a.grade

 a.grade { color: red; } .grade a { color: green; } 
 <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/> <li class="grade"> <a><i class="fa fa-star fa-fw">Text within an &lt;a&gt; descendant of .grade</i></a><br> Text outside of &lt;a&gt; element </li> <a class="grade"> Text in an &lt;a&gt; element, which has the class grade itself. </a> 

Use style like below 使用如下样式

a.grade {
  color : red;
}

Demo : https://jsfiddle.net/e73t9mtk/ 演示: https : //jsfiddle.net/e73t9mtk/

Use typeTag.className for target a element: 使用typeTag.className为目标a元素:

 li.grade { color: red; } li.grade ai { color: green; } a.grade { color: blue; } 
 <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <li class="grade"> <a><i class="fa fa-star fa-fw"></i></a> My Text </li> <a class="grade"> Text here should be white </a> 

Firstly, you never said what color you wanted the i to be, only that you didn't want it to be white. 首先,您从未说过要让i成为什么颜色,只是说您不希望它是白色。 So I'll assume it should be the same color as the body. 因此,我假设它应该与主体具有相同的颜色。 Write this. 写这个。

body, .grade i {
  color:#777;
}

Secondly, if you want not only the a elements inside a .grade white, but only the a s that have class grade themselves, you will have to add a.grade as a selector too. 其次,如果不仅要在.grade白色中包含a元素,而且还想要仅具有自身gradea ,则还必须添加a.grade作为选择器。

.grade a, a.grade {
  color: white;
}

So the complete code to do what you want is as follows. 因此,完成所需操作的完整代码如下。

 html { background:#ddd; } body, .grade i { color:#777; } .grade a, a.grade{ color: white; } 
 <ul> <li class="grade"> <a><i class="fa fa-star fa-fw">(icon goes here)</i></a> My Text </li> </ul> <a class="grade"> Text here should be white </a> 

(Note that I added a bit of text to the icon, to make it visible in the absence of FontAwesome.) (请注意,我在图标上添加了一些文本,以使其在没有FontAwesome的情况下可见。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM