简体   繁体   中英

Positioning a span inside a relatively positioned div

I'm working on a Wordpress plugin and I've come across a problem with positioning a span . Basically, there's a div that holds an img and a span (the div and span are added dynamically in the plugin, but I don't think that's the case here) that should cover the img . The size, float and margins of that span are set dynamically once the image is loaded, so the span covers the image entirely.

Unfortunately, when the image is floated right, has a positive margin-left value and is wider (image+margin) than the div that contains it, there's a problem. The left margin of the image is altered, but the span 's left margin isn't, so the span doesn't cover the image properly. Is there a way to fix this issue or a good workaround? I mean in a way that will work well in other cases, like floating the image left, etc. I've noticed that it works similarly on Chrome, IE9 and FF19.

An example: http://jsfiddle.net/6zQp3/1/

UPDATE I don't think I've explained the issue well enough, so here's another example:

http://jsfiddle.net/6zQp3/53/

I've pointed out which parts of the code I can change and which I can't. Basically, the plugin dynamically creates the div.image-container and span.cover (I've omitted this part here, as it's not really relevant) for every image on the site. The span.cover should cover the image entirely. As you can see in this new example, the first image isn't covered properly, while others are. That's my issue - adjusting the JavaScript and maybe css so it'll work properly in this one case as well. Please note that I cannot modify css of images (so using absolute positioning on images isn't an option).

Your span is positioned as absolute therefore it can't be floated left or right.

Here's my versions for it:

A) http://jsfiddle.net/6zQp3/47/

B) http://jsfiddle.net/6zQp3/49/

Now you can position the img + span anywhere.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM