我有一张图片,我想给它设置一个特定的宽度和高度(像素)
但是如果我使用css (width:150px;高度:100px),图像将被拉伸,并且它可能是丑陋的。
如何使用CSS填充图像到特定的大小,而不是拉伸它?
填充和拉伸图像示例:
原始图像:
拉伸图片:
填充图片:
请注意,在上面的填充图像示例中:首先,图像被调整为150x255(保持长宽比),然后,它裁剪为150x100。
我有一张图片,我想给它设置一个特定的宽度和高度(像素)
但是如果我使用css (width:150px;高度:100px),图像将被拉伸,并且它可能是丑陋的。
如何使用CSS填充图像到特定的大小,而不是拉伸它?
填充和拉伸图像示例:
原始图像:
拉伸图片:
填充图片:
请注意,在上面的填充图像示例中:首先,图像被调整为150x255(保持长宽比),然后,它裁剪为150x100。
当前回答
增强了@afonsoduarte接受的答案。 以防你使用自举
Providing width:100% on the style. This is helpful if you are using bootstrap and want the image to stretch all the available width. Specifying the height property is optional, You can remove/keep it as you need .cover { object-fit: cover; width: 100%; /*height: 300px; optional, you can remove it, but in my case it was good */ } By the way, there is NO need to provide the height and width attributes on the image element because they will be overridden by the style. so it is enough to write something like this. <img class="cover" src="url to img ..." />
其他回答
你可以通过“伸缩”显示来实现。对我来说!:
.avatar-img { display: flex; justify-content: center; align-items: stretch; border-radius: 50%; border: 1px solid #dee2e6; height: 5.5rem; width: 5.5rem; overflow: hidden; } .avatar-img > img { flex-grow: 1; object-fit: cover; } <div> <div class="avatar-img"> <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSqczw3Fb_TYsj0hbPEy0u7Ay2bVq1KurD6hw&usqp=CAU" alt="Test!'s profile photo"> </div> <div class="avatar-img"> <img src="https://i.pinimg.com/236x/a1/37/09/a137098873af3bf6180dd24cbe388ae9--flower-iphone-wallpaper-wallpapers-flowers.jpg" alt="Test!'s profile photo"> </div> </div>
如果您想使用图像作为CSS背景,有一个优雅的解决方案。只需在背景大小CSS3属性中使用cover或include即可。
.container { 宽度:150 px; 身高:100 px; 背景图片:url(“http://i.stack.imgur.com/2OrtT.jpg”); background-size:封面; 平铺方式:不再重演; 背景位置:50% 50%; } < div class = "容器" > < / div >
封面会给你一个放大的图像,包含会给你一个缩小的图像。两者都将保留像素长宽比。
http://jsfiddle.net/uTHqs/(使用封面)
http://jsfiddle.net/HZ2FT/(使用contains)
根据Thomas Fuchs的快速指南,这种方法的优点是对Retina显示器友好。
值得一提的是,浏览器对这两个属性的支持不包括IE6-8。
我帮助构建了一个名为Fillmore的jQuery插件,它在支持它的浏览器中处理背景大小:封面,并为那些不支持它的浏览器提供了一个垫片。看看吧!
你可以使用css属性object-fit。(“设置替换元素的内容,如<img>或<video>,应该如何调整大小以适应其容器。”)
.cover { object-fit:封面; 宽度:50 px; 身高:100 px; } <img src="http://i.stack.imgur.com/2OrtT.jpg" class="cover" width="242" height="363" />
参见这里的例子
IE有一个polyfill: https://github.com/anselmh/object-fit
相关:object-position(指定元素内容在其框内的对齐方式)。
增强了@afonsoduarte接受的答案。 以防你使用自举
Providing width:100% on the style. This is helpful if you are using bootstrap and want the image to stretch all the available width. Specifying the height property is optional, You can remove/keep it as you need .cover { object-fit: cover; width: 100%; /*height: 300px; optional, you can remove it, but in my case it was good */ } By the way, there is NO need to provide the height and width attributes on the image element because they will be overridden by the style. so it is enough to write something like this. <img class="cover" src="url to img ..." />