Alex Rivera | Logout

Allow images in a <div> to be wider than lines of text in the same <div>

Asked 2012-01-22T23:40:53.763
14

I want to fit text in a <div> to the width of the <div>, but fit images in the same <div> to the width of the parent <div>

This diagram should make things clear:

(here's the URL if it's too small: http://dl.dropbox.com/u/2792776/screenshots/2012-01-22_1838.png)

Edit
Report

2 Answers

10

I would solve this one of two ways. Here is idea #1:

CSS

#inner {width:400px; position:relative; float:left;}

HTML:

<div id="inner">
    <img src="awesomeimage.jpg" alt="this awesome image" />
    <p>text goes here</p>
    <img src="awesomeimage.jpg" alt="this awesome image" />
</div>

SCRIPT:

<script>
var imgWidth = $(window).outerWidth();
$('#inner > img').css({
    width : imgWidth + 'px'
});
</script>

This is assuming you have jQuery loaded up, and that you are using Javascript on your site. If you want to adjust the width of the image, for padding, margins, and borders, do so in the variable.

You can have the image scale with the window, like in the example used in this JS fiddle I created for another question: http://jsfiddle.net/D544n/1/

Idea #2: With Out Javascript.

CSS

#outer {width:100%;} /* Outer becomes irrelevant */
#inner {width:100%;}
#inner img {width:100% !important}
#inner * {width:400px;} /* Set all childs to 400 */

HTML:

<div id="outer">
    <div id="inner">
        <img src="awesomeimage.jpg" alt="this awesome image" />
        <p>text goes here</p>
        <img src="awesomeimage.jpg" alt="this awesome image" />
    </div>
</div>

The selector for this was grabbed from another S.O. Question.

I don't think you are going to find a clear, simple way to do this. These are my two best ideas, and it could be solved other ways. If you are heading down this path to organize your content, you might want to re-think your strategy at accomplishing your goal.

answered 2012-03-08T23:55:27.197
5

What if you got rid of the inner div entirely but put a width of 400px on all p tags within the outer div? Then things would flow correctly and the images would be children of the outer div, so they could be limited by its width.

Of course, this could cause some problems if there are a lot of other elements that need to be contained within the 400px area, but if it's just the paragraphs and some headers then you're set.

answered 2012-01-23T01:05:32.257

Your Answer