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)
Answer: Use the CSS max-width Property You can simply use the CSS max-width property to auto-resize a large image so that it can fit into a smaller width <div> container while maintaining its aspect ratio.
If your image doesn't fit the layout, you can resize it in the HTML. One of the simplest ways to resize an image in the HTML is using the height and width attributes on the img tag. These values specify the height and width of the image element. The values are set in px i.e. CSS pixels.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With