无论浏览器大小如何,始终将图像保持为中心

时间:2012-09-12 22:06:08

标签: html css

我想知道是否可以将img保持在div内,无论浏览器大小如何都始终居中?通过居中,我的意思是图像的左/右侧被裁剪以确保图像保持居中而不修改高度。此外,当浏览器宽度小于图像宽度时,是否可以防止出现水平滚动条?

如果我的图片位于CSS中的background-url标记中,我确信这很容易做到,但由于此图片位于SlidesJS轮播内,因此图片必须来自{{1 }} 标签。

目前,只要浏览器宽度大于图像,我就使用img来保持图像居中。一旦浏览器宽度缩小,图像就不会随着缩小的浏览器大小而调整大小。我还没有弄清楚当浏览器宽度太小时如何删除水平滚动条。

这就是我想要实现的目标:http://imgur.com/Nxh5n

这是页面布局的示例:http://imgur.com/r9tYx

我的代码示例:http://jsfiddle.net/9tRZG/

HTML:

margin:0 auto;

CSS:

<div id="wrapper">
    <div id="slides">
        <div class="slides_container">
            <div class="slide"> <!-- Carousel slide #1 -->
                <img src="http://www.placehold.it/200x50/">
            </div>
            <div class="slide"> <!-- Carousel slide #1 -->
                <img src="http://www.placehold.it/200x50/">
            </div>
            <div class="slide"> <!-- Carousel slide #1 -->
                <img src="http://www.placehold.it/200x50/">
            </div>
        </div>
    </div>
</div>​

3 个答案:

答案 0 :(得分:13)

试试这个:http://jsfiddle.net/9tRZG/1/

#wrapper {
    max-width: 200px; /* max-width doesn't behave correctly in legacy IE */
    margin: 0 auto;
}
#wrapper img{
    width:100%;       /* the image will now scale down as its parent gets smaller */
}
​

要裁剪边缘,您可以执行以下操作:http://jsfiddle.net/9tRZG/2/

#wrapper {
    max-width: 600px; /* so this will scale down when the screen resizes */
    margin: 0 auto;
    overflow:hidden;  /* so that the children are cropped */
    border:solid 1px #000; /* you can remove this, I'm only using it to demonstrate the bounding box */
}

#wrapper .slides_container{
    width:600px;            /* static width here */
    position:relative;      /* so we can position it relative to its parent */
    left:50%;               /* centering the box */
    margin-left:-300px;     /* centering the box */
}
#wrapper img{
    display:block;          /* this allows us to use the centering margin trick */
    margin: 2px auto;       /* the top/bottom margin isn't necessary here, but the left/right is */
}

答案 1 :(得分:3)

Jeff Hines联系了putting image always in center page,其中ShankarSangoli解释了如何实现这一目标。

img.centered {
     position:fixed;
     left: 50%;
     top:  50%;
     /*
         if, for instance, the image is 64x64 pixels,
         then "move" it half its width/height to the
         top/left by using negative margins
     */
     margin-left: -32px;
     margin-top:  -32px;
 }

答案 2 :(得分:1)

对于滚动条,我不确定对齐中心对我来说是否合适。 您可以使用以下内容:

overflow-x: hidden;