Search code examples
htmlcssimagewidth

How to match text width to image without specifying exact widths?


I have this HTML:

<article>
  <img src="image.jpg">
  <p> Text </p>
</article>

The text is placed underneath the image. Now I want the text to be the same width as the image, but I do not want to specify an exact width since the images are of different widths (so are the articles).

How can I make the text width correspond to the image width ie. making it break at the right time without specifying an exact width?


Solution

  • I found a CSS only solution. This might not work in all browsers yet, but certainly seems to work in the major ones.

    article {
      width: -moz-min-content;  /* Firefox/Gecko */
      width: -webkit-min-content;   /* Webkit */    
      width: min-content;
    }
    

    See fiddle: http://jsfiddle.net/U2Vxr/

    And a full article on the matter: http://demosthenes.info/blog/662/Design-From-the-Inside-Out-With-CSS-MinContent