开发者

How to set multiline text in floated div not expand his width

开发者 https://www.devze.com 2023-01-27 23:26 出处:网络
I want use floatet image with some text about this image in my content. I\'m using this HTML + CSS for this:

I want use floatet image with some text about this image in my content.

I'm using this HTML + CSS for this:

<p class="container">
<img src="http://www.google.com.ua/images/logos/ps_logo2.png" width="200"/>
<span class="text">Some text wider that image image image blablabla</span>

And CSS for it:

.container { float:r开发者_StackOverflow社区ight; border:2px solid #000; }
.container img { display:block; margin-bottom:10px; }

But, if text about image is wider, it is expand floated parent. I'm not want this behaviour. I want to limit max-width of parent p element to width of image.

Here example on jsfiddle: http://jsfiddle.net/wBVqt/1/

I can do what I want through position:absolute and padding-bottom, but I don't know value for padding-bottom. jsfiddle.net/wBVqt/3/


I don't see solution with only css if you want to have images of different sizes, so chek my solution with jQuery:

var imageWidth = 0;
$('.container img').each(function(index, el){
    if(el.width > imageWidth) {
        imageWidth = el.width;
    }
});
imageWidth = imageWidth ? imageWidth : '100%';

$('.container').css('width', imageWidth);

It will work yet if you have a lot of images in your container. If you have no images, it will set originally 100% width to container.


Have you tried just putting a width on the container? (Which you should do anyway if you want your code to validate, as all floated elemets should have a width).

.container { float:right; border:2px solid #000; width: 200px; }
0

精彩评论

暂无评论...
验证码 换一张
取 消