Avoid Stretch on Image CSS

CSS Image size, how to fill, but not stretch?

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.")

.cover {
object-fit: cover;
width: 50px;
height: 100px;
}
<img src="http://i.stack.imgur.com/2OrtT.jpg" class="cover" width="242" height="363" />

How to set an image's width and height without stretching it?

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; }

Avoid image stretch within a CSS octagon container

Instead of using <img>, include the image as a background-image for a <span> element, and use background-size: cover on it. To position the image, adjust the background-position values.

.octo-image {     display: block;     width: 300px;     height: 300px;     background-position: center center;     background-size: cover;}
* { box-sizing: border-box;}
.octo { transform: rotate(45deg);}
.octo1 { transform: rotate(-45deg);}
.octo, .octo div { margin: 0 auto; transform-origin: 50% 50%; overflow: hidden; width: 300px; height: 300px;}
<div class="octo">     <div class="octo1">          <span class="octo-image" style="background-image: url('https://i.stack.imgur.com/5voQJ.jpg')"></span>      </div></div>


Related Topics



Leave a reply



Submit