rajini raja
rajini raja

Reputation: 99

descendant selector not working

When I try to target all anchor elements inside the p element using a descendant selector. Rules only apply to child elements and not the nested elements.

p a {
  display: inline;
  color: red;
}
<p>
  <a href="http://www.reddit.com">Go to Reddit website</a>
  <a href="http://www.quora.com">Go to QUORA</a>
  <div>
    <a href="http://www.channel9.com">channel9</a> 
  </div>
</p>

Upvotes: 0

Views: 3988

Answers (5)

M. Lak
M. Lak

Reputation: 911

Please use this code instead of above code.

.clr-rd a {
  color: red;
  display: inline;
}
<div class="clr-rd">
  <p>
    <a href="http://www.reddit.com">Go to Reddit website</a>
    <a href="http://www.quora.com">Go to QUORA</a>
    <div>
      <a href="http://www.channel9.com">channel9</a> 
    </div>
  </p>
</div>

Upvotes: 0

pradeep1991singh
pradeep1991singh

Reputation: 8375

Seems your html is invalid, try to replace p with div. It should work. Something like below -

div a {
  display: inline;
  color: red;
}
<div>
  <a href="http://www.reddit.com">Go to Reddit website</a>
  <a href="http://www.quora.com">Go to QUORA</a>
  <div>
    <a href="http://www.channel9.com">channel9</a>  
  </div>
</div>

For details - Why <p> tag can't contain <div> tag inside it?

Upvotes: 0

Clyde Lobo
Clyde Lobo

Reputation: 9174

A p tag cannot have a div tag inside it. Since this is an invalid html your browser corrects that for you. It closes the p tag as soon as it sees the div tag. And also adds a starting p tag for the closing p tag

Your actual HTML

<p>
   <a href="http://www.reddit.com">Go to Reddit website</a>
   <a href="http://www.quora.com">Go to QUORA</a>
   <div>
        <a href="http://www.channel9.com">channel9</a>  
   </div>
</p>

What it actually renders to

<p>
   <a href="http://www.reddit.com">Go to Reddit website</a>
   <a href="http://www.quora.com">Go to QUORA</a>
</p>
<div>
   <a href="http://www.channel9.com">channel9</a>  
</div>
<p></p>

And since the a tag with text channel9 is not inside a p tag, your css does not have any effect

Upvotes: 1

Alex
Alex

Reputation: 471

<p>
   <a href="http://www.reddit.com">Go to Reddit website</a>
   <a href="http://www.quora.com">Go to QUORA</a>
   <div>
        <a href="http://www.channel9.com">channel9</a>  
   </div>
</p>

css

a {
   display: inline;
   color: red;
}

Upvotes: 0

Aslam
Aslam

Reputation: 9682

You cannot use div inside a p element

p a {
  display: inline;
  color: red;
}
<p>
  <a href="http://www.reddit.com">Go to Reddit website</a>
  <a href="http://www.quora.com">Go to QUORA</a>
  <span>
    <a href="http://www.channel9.com">channel9</a> 
  </span>
</p>

Upvotes: 0

Related Questions