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

Jon*_*Jon 7 html css

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

我确信如果我的图像位于background-urlCSS 中的标签中,这很容易做到,但由于此图像位于SlidesJS轮播内,因此图像必须来自img标签.

目前,margin:0 auto;只要浏览器宽度大于图像,我就习惯将图像保持在中心位置.一旦浏览器宽度缩小,图像就不会随着缩小的浏览器大小而调整大小.我还没有弄清楚当浏览器宽度太小时如何删除水平滚动条.

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

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

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

HTML:

<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>?
Run Code Online (Sandbox Code Playgroud)

CSS:

#wrapper {
    width: 200px;
    margin: 0 auto;
}?
Run Code Online (Sandbox Code Playgroud)

Shm*_*dty 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 */
}
?
Run Code Online (Sandbox Code Playgroud)

要裁剪边缘,您可以这样做: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 */
}
Run Code Online (Sandbox Code Playgroud)

  • 为了它的乐趣,我制定了你想要的布局:http://jsfiddle.net/9tRZG/3/ (3认同)