我知道用CSS修改图像是不可能的,这就是为什么我把裁剪放在引号里的原因。
我想做的是采用矩形图像,并使用CSS使它们看起来像正方形,而不扭曲图像。
我想把这个:
到这个:
我知道用CSS修改图像是不可能的,这就是为什么我把裁剪放在引号里的原因。
我想做的是采用矩形图像,并使用CSS使它们看起来像正方形,而不扭曲图像。
我想把这个:
到这个:
当前回答
一个纯CSS解决方案,没有包装div或其他无用的代码:
img {
object-fit: cover;
width: 230px;
height: 230px;
}
其他回答
假设它们不必出现在IMG标签中……
HTML:
<div class="thumb1">
</div>
CSS:
.thumb1 {
background: url(blah.jpg) 50% 50% no-repeat; /* 50% 50% centers image in div */
width: 250px;
height: 250px;
}
.thumb1:hover { YOUR HOVER STYLES HERE }
编辑:如果div需要链接到某个地方,只需调整HTML和样式如下:
HTML:
<div class="thumb1">
<a href="#">Link</a>
</div>
CSS:
.thumb1 {
background: url(blah.jpg) 50% 50% no-repeat; /* 50% 50% centers image in div */
width: 250px;
height: 250px;
}
.thumb1 a {
display: block;
width: 250px;
height: 250px;
}
.thumb1 a:hover { YOUR HOVER STYLES HERE }
注意,这也可以修改为响应,例如%宽度和高度等。
可以使用. 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 >
适合对象:封面正好可以满足你的需要。
但它可能无法在IE/Edge上运行。如下所示,用CSS修复它,使其适用于所有浏览器。
我采用的方法是在容器中使用absolute定位图像,然后使用组合将其放在正中央:
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
一旦它在中心,我给图像,
// For vertical blocks (i.e., where height is greater than width)
height: 100%;
width: auto;
// For Horizontal blocks (i.e., where width is greater than height)
height: auto;
width: 100%;
这使得图像得到对象适合:覆盖的效果。
下面是上述逻辑的演示。
https://jsfiddle.net/furqan_694/s3xLe1gp/
这种逻辑适用于所有浏览器。
原始图像
垂直剪裁
水平的剪裁
方形容器
一个纯CSS解决方案,没有包装div或其他无用的代码:
img {
object-fit: cover;
width: 230px;
height: 230px;
}
现在你可以使用纵横比:
img {
aspect-ratio: 1 / 1;
}
它在现代浏览器中也有广泛的支持: https://caniuse.com/mdn-css_properties_aspect-ratio