tags:

views:

63

answers:

2

With the example below, I need to add padding and background-color properties to the text anchor. I then need to exclude padding and background-color from anchors that contain images.

<p>
  <a href="#">this is a text link that needs to be styled</a>
  <a href="#"><img src="image/name.jpg" alt="this needs to be excluded from styling" /></a>
</p>

If I have a red background and padding on my text links, I do not want that same red background and padding to appear on my linked images. The images will always be in their own anchors, not mixed with text within the same anchor.

The rub is that I can not add classes or IDs to the img tags - I do not have edit control of that data.

So how can I add CSS attributes to all anchors, while excluding anchors that contain images?

+2  A: 

Using JQuery:

$(function() {
    $('a:not(:has(img))').css('background','red');
});
Mr. Shiny and New
Short and sweet. This is great, thank you.
Deca
+2  A: 

Currently, you cannot select the parent of a matched child selector. You'll have to use javascript to accomplish this.

That being said, if your page background is solid, you could use negative margins and a background on your img tags to overlay your a background… Here's the example. I have not tested on all browsers, but it seems to work for me in Safari, Firefox, and MSIE8.

a {
   display: inline;
   padding:10px;
   background:red;
}

a img {
   border: none;
   vertical-align: bottom;
   margin:-10px;
   padding: 0px;
   background:white;
}
ghoppe
This is brilliant, just for the fact that it doesn't require an additional 70k jquery include. Thank you.
Deca
@Deca: Avoiding unnecessary JS files is good, but you shouldn't use the uncompressed jquery; the minified one is 25k. And if you use the one from Google's CDN, there's a chance your users will already have it cached (downside: sometimes Google will find out that your site uses jquery and will see who some of your users are).
Mr. Shiny and New