mellowsoon
mellowsoon

Reputation: 23251

Applying Style to Parent By Selecting Child

It appears some browsers (Chrome at least) put a partial underline under images that are nested inside of an anchor tag, like this:

<a href="#"><img src="/foo.jpg" /></a>

So I'm looking for a way to add text-decoration: none; to any anchor tags that contain an img tag. My first thought was this:

a img {
    text-decoration: none;
}

Of course that doesn't work, because the style gets applied to the img tag, and not the anchor. So is there a selector I can use to apply the text-decoration style to any anchor tag with a img child?

EDIT: My HTML typically looks like this:

<a href="#">
    <img src="/foo.jpg" />
</a>

The way I space and tab the elements is adding extra whitespace between the anchor tag, and image tag. It's that white space that's being underlined.

Upvotes: 0

Views: 1196

Answers (5)

NGLN
NGLN

Reputation: 43649

If the href attribute of these anchors always points to images, and no anchors point to images besides the one with actually an img tag inside, then you can use:

a[href$=".gif"],
a[href$=".png"],
...            ,
a[href$=".jpg"] {
    text-decoration: none;
}

Upvotes: 0

Wex
Wex

Reputation: 15695

If you're against adding a class to this <a> tag (which is the simple solution), your next best CSS solution would be to remove text-decoration on the <a> tag, and wrap the text you want to have underlined in an inline element. See below:

For images:

<a href="#">
  <img src="/foo.jpg" alt="etc" />
</a>

For text:

<a href="#">
  <span>Text that you probably want underlined</span>
</a>

Combined:

<a href="#">
  <img src="/foo.jpg" alt="etc" /> <span>Text that you probably want underlined</span>
</a>

CSS:

a { text-decoration: none; }
a:hover span { text-decoration: underline; }

Upvotes: 3

DavidJCobb
DavidJCobb

Reputation: 1131

So far as I can tell, there is no way to select an element's parent in CSS. You could try applying some class, i.e. imagelink to A elements that contain IMG elements, though.

Upvotes: 0

BonyT
BonyT

Reputation: 10940

Unfortunately there is no way currently of selecting the parent of an element using just CSS.

You would need to resort to javascript or jQuery.

Personally I would do something in jQuery like

 $('a>img').parent().addClass('noTextDecoration');

then in css have the following:

 a.noTextDecoration {test-decoration:none;}

Upvotes: 1

user686605
user686605

Reputation:

I just use

img {
    border:none;
}

Upvotes: 0

Related Questions