CSS how do you stretch to fit and maintain the aspect ratio?
You can use the background-size
property with the contain
value:
background-size: contain;
Here is a working example: https://jsfiddle.net/gusrodriguez/auuk97hf/1/
In the example above, the body has an stretched image in the background. Also there are two divs with arbitrary size, and with another image that fits and keep the aspect ratio.
Does it need to be a background image?
img{
width:300px;
height:auto;
}
<img src="your-photo.png">
This should work (in browsers which support background-size
):
background-size: 175px auto;
You could also try:
background-size: cover;
Or:
background-size: contain;
There's a good explanation on MDC.