6

I'm trying to select all anchor tags that link to external sites that do not have child image tags. If I have an image as a link, it adds the little external link icon next to those images as well, but I don't want that.

This is what I have so far:

a[href^="http://"]{
  background:transparent url(..icon/external.png) center right no-repeat;
  display:inline-block;
  padding-right:18px;
}

As an added bonus, how would I make it work with "https://" links as well?

thirtydot
  • 210,355
  • 44
  • 377
  • 337
MaxGhost
  • 294
  • 5
  • 18
  • 2
    That can't currently be done with CSS. [There's still no parent selector.](http://stackoverflow.com/questions/1014861/is-there-a-css-parent-selector) – thirtydot Aug 09 '12 at 15:52
  • I can't wait for the CSS 4 spec to become standard... seems like there's a ton of cool features to come from there. – MaxGhost Aug 09 '12 at 15:56
  • The padding gives space for the icon on the right side of the link, then the background adds the image itself, aligned to the right. inline-block makes the entire link including the image clickable. [See here for more info](http://web-kreation.com/all/add-file-type-icons-next-to-your-links-with-css/) – MaxGhost Aug 09 '12 at 16:00

1 Answers1

6

This isnt possible with plain CSS. However you could use a bit of jQuery wizardry:

jQuery:

$("a[href^='http://']:not(:has(img))").addClass("external");

CSS:

a.external {
  background:transparent url(..icon/external.png) center right no-repeat;
  display:inline-block;
  padding-right:18px;
}

See Demo: http://jsfiddle.net/hKTBp/

See Demo (including HTTPS): http://jsfiddle.net/hKTBp/1/

Curt
  • 94,964
  • 60
  • 257
  • 340
  • I don't think you can safely assume he has jQuery installed. – kojiro Aug 09 '12 at 15:56
  • 2
    @kojiro I agree, but I can safely say that what the OP wants isn't possible, and I've provided a neat alternative. – Curt Aug 09 '12 at 15:56
  • 1
    Nice fix! I would've preferred a non-JS solution, but this works. I do have jQuery, so this is fine. – MaxGhost Aug 09 '12 at 15:57
  • Actually, how could I also make this match "https://" as well? I'm not sure how to do an AND case with jQuery. – MaxGhost Aug 09 '12 at 16:02
  • 1
    `$("a[href^='http://']:not(:has(img)),a[href^='https://']:not(:has(img))")` or `$("a[href^='http://'],a[href^='https://']").not(":has(img)")` – Curt Aug 09 '12 at 16:05
  • Thanks. I wasn't sure if there was something like `href^='http://' && href^='https://'`, which would be nice to have. – MaxGhost Aug 09 '12 at 16:07
  • 1
    @MaxGhost I'm not sure, so I've posted a question :) http://stackoverflow.com/questions/11887602/jquery-attribute-selector-x-y-or-x-z – Curt Aug 09 '12 at 16:15