在DIV中居中更大的图像

时间:2013-10-01 12:31:30

标签: html css html5 css3 centering

我正试图在一个较小的div中居中(和裁剪)一个大图像。这是我希望它看起来像: enter image description here

图像只是以div为中心;无论图像的大小,都无关紧要。

有什么想法吗?

5 个答案:

答案 0 :(得分:2)

您可以使用transformposition: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%);
}

http://jsfiddle.net/4nH3A/1/

演示

如果您想要裁剪它,也可以将overflow:hidden添加到div

http://jsfiddle.net/4nH3A/2/

演示

答案 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); 
}

http://jsfiddle.net/aWMLA/

答案 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;}