Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fit div to image?

Tags:

html

css

I have a fluid image inside a div, under the image there is an other div with text. Is it possible for the #text div to get same size like the image?

<div id="container">
    <img src="http://dummyimage.com/300x200/c7c1c7/fff.jpg">
    <div id="text">Several standard dimensions are included in dummyimage.com including ad sizes and screen resolution sizes.</div>
</div>


#container {
    display: inline-block;
    height: auto;
    max-width: 100%;
    position: relative;
}

img {
    max-width:100%; max-height:100%;
}

FIDDLE

like image 983
user25381 Avatar asked Jul 05 '13 08:07

user25381


People also ask

How do I fit a div image without stretching it?

How to fit image without stretching and maintain aspect ratio? Answer: If you want to use the image as a CSS background, there is an elegant solution. Simply use cover or contain in the background-size CSS3 property. contain will give you a scaled-down image.


2 Answers

Seeing as the #container is relatively positioned, you could position the #text absolutely, to prevent it from stretching the #container:

#text {
    /* remove from flow, prevents from stretching container */
    position: absolute;
}

http://jsfiddle.net/HUsRm/5/

This will, of course, also prevent vertical stretching, and not push following content down. This might be unwanted?

like image 76
xec Avatar answered Nov 06 '22 19:11

xec


You can make this work by having only this css:

#container
{
    display:table-caption;
}

Fiddle

like image 24
algiecas Avatar answered Nov 06 '22 21:11

algiecas