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

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

我确信如果我的图像位于CSS中的background-url标记中,这很容易做到,但由于此图像位于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>​

CSS:

#wrapper {
    width: 200px;
    margin: 0 auto;
}​

解决方法

试试这个: 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 */
}

相关文章

vue阻止冒泡事件 阻止点击事件的执行 &lt;div @click=&a...
尝试过使用网友说的API接口获取 找到的都是失效了 暂时就使用...
后台我拿的数据是这样的格式: [ {id:1 , parentId: 0, name:...
JAVA下载文件防重复点击,防止多次下载请求,Cookie方式快速简...
Mip是什么意思以及作用有哪些