Can I target a :before or :after pseudo-element with a sibling combinator?

jkupczak picture jkupczak · Oct 12, 2011 · Viewed 11.1k times · Source

Is there a reason why this CSS doesn't work?

http://jsfiddle.net/6v5BZ/

a[href^="http"]:after {
    content:"";
    width:10px;
    height:10px;
    display:inline-block;
    background-color:red;
}

a[href^="http"] img ~ :after {
    display:none;
}

.. on this HTML?

<a href="http://google.com">Test</a>
<a href="http://google.com">
    <img src="https://www.google.com/logos/classicplus.png">
</a>

The idea is to have a pseudo-element on matching anchor tags. But I do not want it to apply to anchor tags that wrap an image. And since I can't target anchors using something like a < img, I figured the maybe I could target the :after pseudo-element by finding an image that it's a sibling of.

Any insight would be greatly appreciated.

Answer

easwee picture easwee · Oct 12, 2011

You can't target :after since it's content is not rendered in the DOM and it does not manipulate it - for this to work the DOM would have to be re-rendered and CSS can't manipulate it like this.

Check the specification for detailed understanding: http://www.w3.org/TR/CSS2/generate.html#propdef-content

Generated content does not alter the document tree. In particular, it is not fed back to the document language processor (e.g., for reparsing).

I suggest you use JavaScript to do the job for you.