Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML/CSS <p> width of an image

Tags:

html

css

I'm working on a site that places an image in a div and beneath the image is an <p> tag with some text in it. The pictures can be 150px wide or 200px wide but the <p> tag should not be wider then the image because then it messes up the layout. So I'm not sure what to do, the width of the images is dynamic so I can't put a width on anywhere, so I may have to resort to javascript to get the width of the image and put that width on the <p> tag but javascript isn't really my strong suit so I'm hoping for a simple css solution.

Here's a bit of code so you guys can see how it looks.

<li>
    <div class="container_movie">
        <img src="images/category/movie/super-8-cover.jpg"/>
        <p> super8<br/>
        22-07-’11 <span class="day_countdown">// 11 days</span></p>
    </div>
</li>

Also I know the code isn't perfect yet, I'm still testing a lot.

like image 981
Peter Boomsma Avatar asked Jul 18 '11 10:07

Peter Boomsma


2 Answers

I fear you won't be able to escape using client side scripting.

The most simple way is setting the container <div> width when the image loads.. for this, first add ID to the container:

<div id="container_movie" class="container_movie">

Then this simple onload event for the image:

<img src="...source here..." onload="document.getElementById('container_movie').style.width = this.width + 'px'" />

Live test case: http://jsfiddle.net/jqy48/1/

like image 167
Shadow Wizard Hates Omicron Avatar answered Oct 06 '22 20:10

Shadow Wizard Hates Omicron


If you decide use javascript you can use something like this (code is very ugly and it's meant only for illustrating the idea):

<script>
    function onImgLoad (img) {
        img.parentNode.lastChild.style.width = img.width + 'px';
    }
</script>
<div class="container_movie">
        <img src="http://t2.gstatic.com/images?q=tbn:ANd9GcQZLVgU_LoiQ7VDF6UQSqUWTN-ZqL2FWnBThQgL6F0G5803L-nR" onLoad="onImgLoad(this)"/>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ultrices vulputate pretium. In sagittis faucibus justo, ac dignissim erat feugiat eu. </p></div>
like image 23
Molecular Man Avatar answered Oct 06 '22 20:10

Molecular Man