If I have:
#logo {
width: 400px;
height: 200px;
}
then
2017 answer
CSS object fit works in all current browsers. It allows the img
element to be larger without stretching the image.
You can add object-fit: cover;
to your CSS.
you can try setting the padding instead of the height/width.
What I can think of is to stretch either width or height and let it resize in ratio-aspect. There will be some white space on the sides. Something like how a Wide screen displays a resolution of 1024x768.
Do I have to add an encapsulating <div> or <span>?
I think you do. The only thing that comes to mind is padding, but for that you would have to know the image's dimensions beforehand.
Make a div and give it a class. Then drop a img in it.
<div class="mydiv">
<img src="location/of/your/image" ></img>
</div>
Set the size of your div and make it relative.
.mydiv {
position: relative;
height:300px;
width: 100%;
overflow: hidden;
}
then style your image
img {
width: 100%;
height: auto;
overflow: hidden;
}
Hope that helps
#logo {
width: 400px;
height: 200px;
/*Scale down will take the necessary specified space that is 400px x 200px without stretching the image*/
object-fit:scale-down;
}