Alessandro Colavito
Alessandro Colavito

Reputation: 43

CSS img not direct child of

I'd like to select a img child of #boardMostra but not direct child of a tag a.

I tried this :

#boardMostra img :not(a img:first-child){
  ...
}

But it doesn't work.

Upvotes: 3

Views: 4552

Answers (2)

Partik
Partik

Reputation: 836

Solution:

#boardMostra > img , #boardMostra :not(a) > img { ... }

The first part refers to <img>s that are direct descendants of #boardMostra.

The second part refers to all <img>s in #boardMostra that are direct descendants of anything but <a>

See an example: https://jsfiddle.net/t4snrgz6/

Why I think this is better than the accepted answer

There are times when you don't want to manually write out the CSS for the alternative set. For example, I am using a plugin that has a bunch of CSS for <code> elements that are direct descendants of <pre> elements. I want to style <code> elements that are NOT direct descendants of <pre> without messing with the plugin's CSS. My solution allows me to do that, using :not(pre) > code

Upvotes: 1

Farzad Yousefzadeh
Farzad Yousefzadeh

Reputation: 2561

The only css way you could use is to set a property on #boardMostra img and neutralize it on #boardMostra a > img.

An example

<div>
    <img src="#" alt="#">
    <a href="#"><img src="#" alt="#"></a>
</div>

div img { margin: 10px 20px; }
div a > img { margin: 0; }

Explanation

Why your example code doesn't work:

The :not(X) property in CSS is a negation pseudo class and accepts a simple selector1 as an argument. Essentially, just another selector of any kind.

:not matches an element that is not represented by the argument. The passed argument may not contain additonal selectors or any pseudo-element selectors.

Source: https://css-tricks.com/almanac/selectors/n/not/

Upvotes: 5

Related Questions