If I have:
#logo { width: 400px; height: 200px; }
then
<img id="logo" src="logo.jpg"/>
will stretch to fill that space. I want the image to stay the same size, but for it to take up that much space in the DOM. Do I have to add an encapsulating <div>
or <span>
? I hate adding markup for styling.
You can use the css property object-fit . ("sets how the content of a replaced element, such as an <img> or <video> , should be resized to fit its container.") Related: object-position (specifies the alignment of an element's contents within its box.)
container { width: 50%; } . container img { width: 100%; height: 400px; //this should be the same as the width value.. }
The Simple Solution Using CSSBy setting the width property to 100%, you are telling the image to take up all the horizontal space that is available. With the height property set to auto, your image's height changes proportionally with the width to ensure the aspect ratio is maintained.
Yes you need an encapsulating div:
<div id="logo"><img src="logo.jpg"></div>
with something like:
#logo { height: 100px; width: 200px; overflow: hidden; }
Other solutions (padding, margin) are more tedious (in that you need to calculate the right value based on the image's dimensions) but also don't effectively allow the container to be smaller than the image.
Also, the above can be adapted much more easily for different layouts. For example, if you want the image at the bottom right:
#logo { position: relative; height: 100px; width: 200px; } #logo img { position: absolute; right: 0; bottom: 0; }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With