JasonDavis
JasonDavis

Reputation: 48933

Resize an image based on the size of the DIV it is in with CSS?

Below is an image of a blog I am working on. I need help with some CSS though. In the top image you can see what happens to my avatar when the text body to the right of it is larger then the image.

The bottom image is how I want it to look.

My problem is there are multiple authors, so the body text to the right can be of different lengths depending on the author. I would like to somehow have the image re-size itself to always fit into the div and look like it does in the bottom image.

Hopefully that all made sense, if anyone knows how to do this I would appreciate any help

I also put some example code up here to see it live http://dabblet.com/gist/2050005

enter image description here

Upvotes: 5

Views: 3773

Answers (4)

Flavio
Flavio

Reputation: 51

I am using this:

.product p.image {
text-align: center;
width: 220px;
height: 160px;
overflow: hidden;
}
.product p.image img{
max-width: 100%;
max-height: 100%;
}

Upvotes: 0

Swarup
Swarup

Reputation: 11

This will work for you ..

Use css for setting

img { max-width: 100%; max-height:100% }

Upvotes: 1

Tango Bravo
Tango Bravo

Reputation: 3309

Why can't you just do:

<!doctype html>
<html>
    <head>
        <style type="text/css">
            #img-div { width: 250px; }
            #img-div img { width: 100%; }
            #text-div {  }
        </style>
    </head>
    <body>
        <div id="img-div">
            <img src="example.jpg" />
        </div>
        <div id="text-div">
            Lorem ipsum dolor blah blah blah
        </div>
    </body>
</html>

That works for me. The only issue is when the actual image is smaller than the width of the containing div, then it gets pixelated.

Upvotes: 0

JT Smith
JT Smith

Reputation: 741

Force the image to a specific size, regardless of the size of the original.

css:

.size-image img {
width: 200px;
height: 200px;
}

Size being whatever size you need/want to fill. In the html just add the class to the img element.

<img src="path/to/image" class="size-image" />

Then any image put into that element, whether by jquery, php or whatever, the element is sized to specifically what you need/want.

You can also put the image in it's own container, say "left-container" and have the width of the left container a specific width with an auto height, only put the <img> tag in the left container and the text in the "right-container"

Hope this helps

Upvotes: 2

Related Questions