Erin Call
Erin Call

Reputation: 1784

Set element width to image inside it

I have a page that displays an image, along with some metadata about it. The image and metadata should be centered in the page. I'd like the div containing the metadata to be exactly as wide as the image. Sorta like so:

mockup

Unfortunately, it's not possible for me to reliably determine the image's width before serving the page. Right now I'm using a listener on load:

$('.image-container img').one('load', function() {
    $('.image-container, .image-container *').css('max-width', $(this).width());
});

This works, but if the image is large and takes a while to load, the page looks crappy until it finishes. So I'm looking for either:

  1. A way to use CSS to express that the container should be exactly as wide as the image inside it.
  2. An event that fires as soon as the browser gets enough information to know the image's width (which is pretty early on, from what I can see).

Thanks!

Upvotes: 1

Views: 61

Answers (1)

Alvaro Menéndez
Alvaro Menéndez

Reputation: 9012

This is quite easy to do without any jquery. just set the container to display:inline-block like this:

div {display:inline-block; margin:0; padding:0;}

Example in this fiddle (image size 600px x400px)

Upvotes: 1

Related Questions