The situation is I have an img and I want a pop-over caption-box whose width is the width of the img. I can't add the caption as a child of the img, because img tags don't take children. Hence my idea was to have something like this:
<div> <img/> <div> ...caption... <div> </div>
The problem is the outer divs expand to fill the width of their parent, as block elements do, and hence the caption-div becomes equally wide, and I get something that looks like this:
Where the outer div becomes the width of the page, the caption follows the width of the outer div and thus sticks out of the image.
I do not want to manually set the width of the outer div, because I am using this sub-template for images of all shapes and sizes all over the site. Is there anyway to make the outer-div hug the image, rather than fill his parent?
Those images on the site you linked to are actual size, so the simple answer is just to resize the image. You can't really do this without "stretching" the image if the image happens to be less than 300px wide or tall, but you can do it without changing the ratio, which is what I think you mean.
To auto-resize an image or a video to fit in a div container use object-fit property. It is used to specify how an image or video fits in the container. object-fit property: This property is used to specify how an image or video resize and fit the container.
Answer: Use the CSS max-width Property You can simply use the CSS max-width property to auto-resize a large image so that it can fit into a smaller width <div> container while maintaining its aspect ratio.
Something link this: usign height: auto and width: 100% Makes the elemnt fit any size.
I do not want to manually set the width of the outer div, because I am using this sub-template for images of all shapes and sizes all over the site. Is there anyway to make the outer-div hug the image, rather than fill his parent?
You need display: inline-block
combined with text-align: center
.
See: http://jsfiddle.net/thirtydot/V3XyK/
HTML:
<div class="imageContainer"> <div> <img src=".." /> <span>...caption...</span> </div> </div>
CSS:
.imageContainer { text-align: center; } .imageContainer img { display: block; } .imageContainer div { position: relative; display: inline-block; /* if you need ie6/7 support */ *display: inline; zoom: 1; } .imageContainer span { position: absolute; left: 0; bottom: 0; width: 100%; background: #000; background: rgba(0,0,0,.5); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With