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
In Sass, What's The Difference Between The @Mixin and @Extend Directives
How to Write CSS Keyframes to Indeterminate Material Design Progress Bar
Page-Break-After Not Working in Flexboxes
CSS: Placing an Arrow/Triangle with Border on The Top of My Drop Down Menu
Why Clear: Right Doesn't Work as Intended
How to Use Nth-Child in CSS to Select All Elements After The 3Rd One
Em Vs Px... for Mobile Browsers
How to Create CSS3 Bounce Effect
Change Input Placeholder Color Darker
Remove Underline in Inputtext in React Native
CSS - Centering a Page - Then Making The Page 100% Height
How to Hide One Column from Grid in Bootstrap Mobile Version
Angular Material Overriding Default Style of Snackbar Component