1

This is hard to sum up in a title, so forgive me.

Basically, here is what I have:

a img {
/ * style * /
}

However, I want to affect the a tag in this instance. Is there any way to do so in CSS without resorting to JavaScript wizardry?

alex
  • 438,662
  • 188
  • 837
  • 957
arjs
  • 2,625
  • 4
  • 18
  • 18

3 Answers3

5

Unfortunately the cascading in CSS only goes one way. From your example, I'm guessing you are trying to do something like this:

<a><img src="icon.gif">Hello</a> <!-- This A has a taller line height for the icon -->

<a>Hello</a> <!-- This A is normal -->

Most developers would accomplish it by simply adding a class.

<a class="icon"><img src="icon.gif">Hello</a> <!-- This A has a taller line height for the icon -->

Even better, use that class to make the icon a background image and add padding.

<style type="text/css">
a.icon { background:18px left center no-repeat; line-height:18px; }
</style>

<a class="icon" style="background-image:url('icon.gif');">Hello with icon</a>

Put all your icon images into classes too and you have some pretty clean HTML!

Nicole
  • 30,999
  • 11
  • 69
  • 94
  • Actually what I wanted to do was center a linked image. Currently, I'm margin: auto-ing the left and right sides, but when that's done, the entire space to the left and right of the image is linked as well. Good answer though! – arjs Nov 30 '10 at 07:46
4

You want to apply styles to the tag only if it has an image correct? In short, using straight CSS there is no way to do that.

EDIT

BUT, if you wanted to do this w/ jquery you could do it like so:

$('a').has('img').addClass('hasImg');

then use .hasImg as your hook

a.hasImg{background:lime;display:block;height:200px;width:200px;}

Here's a demo on JSBin I put together (view source): http://jsbin.com/owafi4

jyoseph
  • 5,354
  • 9
  • 41
  • 62
  • @andrex , yep, you have to traverse to find that , as jyoseph said its not possible with plain css. – kobe Nov 30 '10 at 01:04
  • If you use JQuery beware the funky appearance of modifying the page on `ready` - on slower connections especially, you will see everything transform after the page is done loading. – Nicole Nov 30 '10 at 01:13
  • I really don't want to include extra JS, I guess I'll just add a class. – arjs Nov 30 '10 at 07:48
1

CSS selectors can not ascend. It is a limitation of the language.

alex
  • 438,662
  • 188
  • 837
  • 957