Can you target CSS by alignment? (Images with alignment-specific margin/padding)

Hi! I disappeared for a while but now I’m back with a question.

For images placed within a block of text, either left-aligned (default) or right-aligned, is there a way to target images (or anything really) with CSS based on their alignment? I realize that this is not likely. In the last six years I’ve never seen anything that specific for CSS but I thought I’d ask. shrug

I’ve encountered this situation many times over the years, and I always just make classes to float the image left or right and add the appropriate padding (with no padding where the image meets the edge of the container div).

The attached diagram probably explains the use it better than I can in words. [Blue is the container div, red is padding or margin around the image, text wraps around the images when they are aligned (or floated).]

It would be nice to have the padding/margin automatically added, tailored to the image’s alignment rather than needing to add special classes to each image. I don’t have a problem with the class method normally, but now I’ve got a project that will be handed off to someone else and unfortunately they have shown that even if I give them the classes and descriptions they won’t use them and will mangle things trying to get it to look right on their own - the more I can assign to be automatic the better.

Since I kind of doubt there’s a way to target by alignment, how do you guys usually handle alignment issues like this? Just live with extra padding/margins on all sides of your images? Rely on specific classes like I do? Or is there a better way to do all this?

Thanks Stevie D. That’s a good point about IE6. adds new rule for that I’ll have to try and remember it for the next time I need to use this method (which will probably be soon, haha).

Ok, I think I just found an answer to my own question. XP That happens too often on here… haha.

Looks like there are attribute selectors which are able to be specific enough like that. I wish I knew about this years ago. I know how to use descendant selectors and pseudo-classes, but knew that they weren’t specific enough to target stuff like alignment. Now I need to go through and read that whole document and see if there’s anything else I can use. :smiley:

So I’m able to use img[align=left] or img[align=right] to target images by alignment defined in the HTML, no extra work for the other guy too so he can’t mess this up that easily. SWEET.

img[align=left] {margin:1em 1em 1em 0;}
img[align=right] {margin:1em 0 1em 1em;}

I see you’ve found the solution yourself (well done!) - however, just a word of warning, this method doesn’t work in IE6 and below, so you might want to include an IE<=6 rule that gives a margin all the way round the image.