csscss-selectorsdescendant

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>


Solution

  • 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?