March 31, 2012

Shrink-to-fit div and paragraph, based on image?

Question by colindunnn

The code below is a simplified version of my website. On my site, the image width varies from page to page and the text is around 100 words. That means the paragraph stretches the DIV to be wider than the image. Using only CSS, is it possible to shrink the DIV and the paragraph to the width of the image?

JSFiddle here

Example of what I’m trying to describe here. Top is what I’m getting, bottom is what I want.

HTML

<div>
    <img src="image.jpg" />
    <p>Lorem ipsum dolor sit amet.</p>
</div>

CSS

div {
   display: inline-block;
   }

Answer by mikevoermans

And for doing anything table related I shall forever shame myself: http://jsfiddle.net/WM6hK/3/

div {
display: table;
border: 1px solid red;
width: 1%;
}

p {
border: 1px solid blue;
}​

Answer by Starx

Right now its not possible, using CSS

Using jQuery, its as easy as this

$("div").width($("div img").width());

Demo

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!