Keep image original size inside smaller div

房东的猫 提交于 2021-01-27 04:47:14

问题


I have an image that is 600x400px, and want it inside a smaller div of size 240x200px, but the image shrinks or gets distorted. I want the original size image centered in the smaller div, which would hide some of the image

I wrote this CSS rule to apply to different image sizes.

.theBox {
   float: left;
   overflow: hidden;
   width: 240px;
   height: 200px;
}

.theBox img {
   display: block;
   height:100% !important;
   width:100% !important;
 }

回答1:


If you specify a 100% size for your image. Your image will then take 100% of its container.

The thing you want is keeping your file at its original size, so do not specify any size for your image.

overflow:hidden is the key to show only a part of your image.

If you want to always have the center of your image visible, you should take a look at this CSS3 property transform:translate(-50%,-50%) with a proper positioning.

Take a look at this jsfiddle and tell me if it can help you.


Edit: With 2020 modern browser, it may be useful to take a look at the CSS object-fit property. In particular object-fit: cover;. Take a look at this updated jsfiddle.




回答2:


To maintain the aspect ratio, only size one dimension, the browser will size the other to maintain the aspect ratio. With the dimensions you have given you'll need to set the height to fit the container (as opposed to the width) so not to have any gaps:

.theBox img {
    display: block;
    height: 100%;
}

Example: jsfiddle




回答3:


If you specify a 100% size for your image. Your image will then take 100% of its container. In order to maintain the actual size, you should write an inline style like this: style="width: auto"



来源:https://stackoverflow.com/questions/24249635/keep-image-original-size-inside-smaller-div

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!