适应固定大小的div容器的图像尺寸

3
我有一个高度为45像素,宽度为60像素的固定大小的`
`,没有其他CSS样式。这个`
`用来显示客户上传的图片。我想提供图片的尺寸,以便上传的图片能够完美地适应给定的`
`。我需要提供优化的尺寸,以便图片在`
`中看起来很好。我首先尝试了给出45x60,90x120等图片的尺寸。请问解决这个问题的正确方法是什么?请指导。谢谢。

我不完全理解你的问题。您想要确定用户上传的图像的正确比例吗?您是否会对图像进行调整大小,或者只接受特定尺寸的图像? - Ashwin
你想要在 Div 中垂直和水平地适应图像吗? - Dinesh Kanivu
3个回答

6

div {
  width: 160px;
  height: 145px;
  overflow: hidden;
  border: 1px solid black;
}

div img {
    width: 100%;
    min-height: 100%;
}
<div>
<img src="https://istack.dev59.com/aFYTl.webp?s=328&g=1"/>
</div>


2

最好的事情如下:

#div-to-contain-image img {
    display: block;
    height: auto;
    min-width: 100%;
    width: 100%;
}

这将尽可能地展现最佳图片。如果您需要完全覆盖包含的div,可以执行以下操作:
#div-to-contain-image img {
    display: block;
    height: 100%;
    width: 100%;
}

1
我为您提供多种图像缩略图设置的解决方案。也许这对您有所帮助。
解决方案#1: 图像在div内垂直和水平居中
.thumb-container {
        position: relative;
        width: 60px;
        padding-bottom:45px; /* padding is using for the height of image */
        margin: 0px;
        overflow: hidden;
        border: 1px solid black;
    }
    .thumb-img {
        position: absolute;
        width: 100%;
        height: 100%;
        border-radius: 0px;
        padding: 0px;
        overflow: hidden;
        border: 0px;
    }
    .thumb-img img {
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        margin: auto;
        width: auto;
        max-width: 100%;
    }

HTML是指超文本标记语言。
<div class="thumb-container">
                                                            <div class="thumb-img"><img src="https://placeholdit.imgix.net/~text?txtsize=47&txt=500%C3%97900&w=80&h=50"></div>
                                                        </div>

在Jsfiddle上查看 https://jsfiddle.net/5az8u7bj/

解决方案#2: 图像垂直和水平居中,width:100%使图像完全覆盖图像框,没有白边。

.thumb-container {
           position: relative;
           padding-bottom:45px;
           margin: 0px;
           overflow: hidden;
           border: 1px solid black;
           width:60px;
        }
        .thumb-img {
            position: absolute;
            width: 100%;
            height: 100%;
            border-radius: 0px;
            padding: 0px;
            overflow: hidden;
            border: 0px;
        }
        .thumb-img img {
            position: absolute;
            top: 0;
            bottom: 0;
            left: -100%;
            right: -100%;
            height:100%;
            margin: auto;
            width: auto;
        }

HTML

<div class="thumb-container">
                                                            <div class="thumb-img"><img src="https://placeholdit.imgix.net/~text?txtsize=47&txt=500%C3%97900&w=500&h=200"></div>
                                                        </div>

在JSFiddle上查看https://jsfiddle.net/2d6x3fn6/1/

也许这些解决方案对你有帮助


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接