WebQube
WebQube

Reputation: 8991

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

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

The bootsrap i star element is painted white. And I don't want it to.

How can I only specify element with a of class .grade

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

and not other elements?

Upvotes: 0

Views: 3337

Answers (4)

Ehsan
Ehsan

Reputation: 12969

Use typeTag.className for target a element:

li.grade {
    color: red;
}

li.grade a i {
    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>

Upvotes: 1

Mr Lister
Mr Lister

Reputation: 46609

Firstly, you never said what color you wanted the i to be, only that you didn't want it to be white. 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 as that have class grade themselves, you will have to add a.grade as a selector too.

.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.)

Upvotes: 0

Chava Geldzahler
Chava Geldzahler

Reputation: 3730

As is, you are selecting any a element which is a descendant of an element with the class grade.

To specify an a element that has the grade class itself, change your selector to:

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>

Upvotes: 4

RahulB
RahulB

Reputation: 2110

Use style like below

a.grade {
  color : red;
}

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

Upvotes: 0

Related Questions