Reputation: 13986
I'm trying to brush up on css and want to know if this is possible with css only:
Let's say I have an image that I want to display in a 100x100
pixel div tag. I'm not sure what the image will be, but if it's smaller than 100x100
pixels, I want it to center the image. If the image is larger, I want it to shrink it to the size of the of the window.
For instance if it's larger:
And if it's smaller:
Is this possible with css alone?
Upvotes: 2
Views: 206
Reputation: 10180
Try this:
CSS
div {
max-width: 100px;
max-height: 100px;
}
img {
width: 100px;
display: block;
margin-left: auto;
margin-right: auto;
border: solid 1px #000;
}
HTML
<div>
<img src="image source1" alt="enter image description here">
</div>
<br>
<div>
<img src="image source2" alt="enter image description here">
</div>
And the JSFiddle
The top image is originally 100px by 100px and the bottom is originally 75px by 75px.
Edit
Oops, had my CSS backwards on the fiddle. It's updated now.
Upvotes: 1
Reputation: 207943
Sure, not a problem. Try this:
CSS
div {
display: table-cell;
vertical-align: middle;
border:1px solid #999;
width:100px;
height:100px;
text-align:center;
font-size:0;
}
img {
max-width:100px;
}
HTML
<div>
<img src="http://www.placekitten.com/200/200" />
</div>
<div>
<img src="http://www.placekitten.com/50/50" />
</div>
jsFiddle example with two images, one 50x50 and the other 200x200
Upvotes: 3