我正试图在一个较小的div中居中(和裁剪)一个大图像。这是我希望它看起来像:
图像只是以div为中心;无论图像的大小,都无关紧要。
有什么想法吗?
答案 0 :(得分:2)
您可以使用transform
与position:absolute
结合使用
<div class="container">
<img src="http://lorempixel.com/500/400/sports/1/" />
</div>
和
.container {
width:200px;
height:200px;
position:relative;
}
.container img {
/*position it starting at the center*/
position:absolute;
left:50%;
top:50%;
/*move it back by 50% of the image*/
transform-origin: 50% 50%;
transform:translate(-50%,-50%);
}
演示
如果您想要裁剪它,也可以将overflow:hidden
添加到div
。
答案 1 :(得分:1)
如果您能够使用css background-image
,这非常简单:
.box1, .box2 {
width: 100px;
height: 100px;
background-position: center;
background-repeat: no-repeat;
}
.box1 {
/* 300x300 image centered in div (cropped) */
background-image: url(http://lorempixel.com/300/300);
}
.box2 {
/* 50x50 image centered in div (not cropped) */
background-image: url(http://lorempixel.com/50/50);
}
答案 2 :(得分:0)
尝试坚持标准的CSS布局。如果你试图使用溢出“可见”来运行“元素”,那将会出现问题。
您应该尝试HTML5画布:drawImage()
对裁剪和调整大小都很有用。
答案 3 :(得分:0)
background-image:center;
或
text-align:center;
答案 4 :(得分:0)
您可以这样使用:
<div id="myimg"></div>
CSS
#myimg{width: 200px; height: 200px; background: url() no-repeat center; background-size: cover;}