Reputation: 211
I have a structure where there are only images like below for desktop view and mobile view with a fixed height respectively in both views.
In mobile view images come out stretched. I have applied a couple of solutions where images get cropped either from top, bottom, left and right and in my case i don't want. How should i proceed so that images do not stretch in any view?
Upvotes: 1
Views: 88
Reputation: 87191
Assuming you want a fixed layout (as in your image), you can use background-image
/background-size
and set it like this
background: url(...) no-repeat; /* the shorthand property */
background-size: cover;
background-position: center center;
The cover
value make the image always fill the element without stretching it and with background-position
you can control whether an image should be centered, left, right, bottom, top aligned
div {
height: 200px;
width: 500px;
background: url(http://lorempixel.com/300/400/animals/4) no-repeat;
background-size: cover;
background-position: center center;
border: 1px solid black;
}
div ~ div {
height: 200px;
width: 200px;
}
div ~ div ~ div {
height: 500px;
width: 200px;
background-position: left center;
}
<div></div>
<div></div>
<div></div>
If you don't want to crop, you can use background-size: contain
instead.
div {
height: 200px;
width: 500px;
background: url(http://lorempixel.com/300/400/animals/4) no-repeat;
background-size: contain;
background-position: left bottom;
border: 1px solid black;
}
div ~ div {
height: 200px;
width: 200px;
}
div ~ div ~ div {
height: 500px;
width: 200px;
}
<div></div>
<div></div>
<div></div>
Update based on comment, using percent height (relative to the body) on an img
html, body {
margin: 0;
height: 100%;
}
img {
height: 40%;
width: auto;
}
<img src="http://lorempixel.com/200/400/animals/4" alt="">
<img src="http://lorempixel.com/300/300/animals/4" alt="">
<img src="http://lorempixel.com/400/200/animals/4" alt="">
Upvotes: 2