我知道用CSS修改图像是不可能的,这就是为什么我把裁剪放在引号里的原因。
我想做的是采用矩形图像,并使用CSS使它们看起来像正方形,而不扭曲图像。
我想把这个:
到这个:
我知道用CSS修改图像是不可能的,这就是为什么我把裁剪放在引号里的原因。
我想做的是采用矩形图像,并使用CSS使它们看起来像正方形,而不扭曲图像。
我想把这个:
到这个:
当前回答
如果图像在一个具有响应宽度的容器中:
.rect-img-container { 位置:相对; } {后.rect-img-container:: 内容:“”; 显示:块; padding-bottom: 100%; } .rect-img { 位置:绝对的; 宽度:100%; 高度:100%; object-fit:封面; } < div class = " rect-img-container”> <img class="rect-img" src="https://picsum。照片/ id / 0/367/267”alt = " " > < / div >
(编辑:从sass更新为纯css) (编辑:添加了虚拟图像供参考)
其他回答
可以使用. testg类中的正方形尺寸的div:
.test {
width: 307px;
height: 307px;
overflow:hidden
}
.testimg {
margin-left: -76px
}
或者一个正方形的div与图像的背景。
.test2 {
width: 307px;
height: 307px;
background: url(http://i.stack.imgur.com/GA6bB.png) 50% 50%
}
这里有一些例子:http://jsfiddle.net/QqCLC/1/
更新以便图像中心
test { 宽度:307 px; 身高:307 px; 隐藏溢出: } .testimg { margin-left: -76像素 } .test2 { 宽度:307 px; 身高:307 px; background: url(http://i.stack.imgur.com/GA6bB.png } <div class="test"><img src="http://i.stack.imgur.com/GA6bB.png" width="460" height="307" class=" testg " /></div> < div class = " test2 " > < / div >
使用background-size:cover - http://codepen.io/anon/pen/RNyKzB
CSS:
.image-container {
background-image: url('http://i.stack.imgur.com/GA6bB.png');
background-size:cover;
background-repeat:no-repeat;
width:250px;
height:250px;
}
标记:
<div class="image-container"></div>
使用CSS: overflow:
.thumb {
width:230px;
height:230px;
overflow:hidden
}
实际上,我最近遇到了同样的问题,最后用了一个稍微不同的方法(我不能使用背景图像)。它确实需要一点jQuery来确定图像的方向(我相信你可以使用纯JS代替)。
我写了一篇关于它的博客文章,如果你有兴趣更多的解释,但代码非常简单:
HTML:
<ul class="cropped-images">
<li><img src="http://fredparke.com/sites/default/files/cat-portrait.jpg" /></li>
<li><img src="http://fredparke.com/sites/default/files/cat-landscape.jpg" /></li>
</ul>
CSS:
li {
width: 150px; // Or whatever you want.
height: 150px; // Or whatever you want.
overflow: hidden;
margin: 10px;
display: inline-block;
vertical-align: top;
}
li img {
max-width: 100%;
height: auto;
width: auto;
}
li img.landscape {
max-width: none;
max-height: 100%;
}
jQuery:
$( document ).ready(function() {
$('.cropped-images img').each(function() {
if ($(this).width() > $(this).height()) {
$(this).addClass('landscape');
}
});
});
如果图像在一个具有响应宽度的容器中:
.rect-img-container { 位置:相对; } {后.rect-img-container:: 内容:“”; 显示:块; padding-bottom: 100%; } .rect-img { 位置:绝对的; 宽度:100%; 高度:100%; object-fit:封面; } < div class = " rect-img-container”> <img class="rect-img" src="https://picsum。照片/ id / 0/367/267”alt = " " > < / div >
(编辑:从sass更新为纯css) (编辑:添加了虚拟图像供参考)