Logical AND for CSS3

css, css-selectors, html

Solution

Unfortunately, you can't achieve this using a CSS selector with a single rule. Currently you can only target `a` elements without the class using `a:not(.redLink)`.

It is not possible to target `a` elements that do not have any `.redLink` ancestors, because the `:not()` pseudo-class doesn't accept combinators (otherwise you would do `a:not(.redLink a)`). A selector like `:not(.redLink) a` wouldn't work either, because that targets `a` elements with at least one ancestor without the class, which is not the same as `a` elements that have no ancestors with the class.

For example if your structure looked like this:

<div class='redLink'>
    <p>
        <a href='#'>Link</a>
    </p>
</div>

That `p` doesn't have the class, so `:not(.redLink) a` would match.

If you happen to have the option of using jQuery, though, `$('a:not(.redLink, .redLink a)')` will work, because `:not()` is much more permissive in jQuery than in CSS.

If you need to do this using CSS only, the easiest solution is to make all `a` elements green, then override it:

a {
    color: green;
}

a.redLink, .redLink a {
    color: red;
}

Problem

I have a quite interesting problem here. I want to target elements that match two conditions at the same time, but I can not find the way ``` <div class='redLink'> <!-- ... ... ... --> <a href='#'>Link</a> <!-- ... ... ... --> </div> <div> <!-- ... ... ... --> <a href='#' class='redLink'>Link</a> <!-- ... ... ... --> </div> ``` My ideal CSS would be ``` [*:not(.redLink) a] AND [* a:not(.redLink)] { color:green; /* i.e., color NOT red */ } ``` However, the operand `,` is just an `OR` (and, when it doesn't match one condition, it matches the other...!). And the only `AND` I can find is the logical concatenation `div#myDivId.someClass`, though what I would like is something like `[div#myDiv a].[div.someClass a]` My goal is to target ONLY those anchors `<a/>` that don't have the class `.redLink` and have no parents with the `.redLink` class eiher. And, very important, the only thing I want to target is the final anchor, not the whole div or the whole `element.redLink`... Thank you!

Original source

Related problems