无论浏览器窗口大小如何,如何在div内自动居中img?

时间:2012-11-09 06:34:02

标签: window size image center

我有一个带有标题,内容和页脚div的html文档。我试图将我的标题div中的图像(徽标)居中显示在我中间网页的顶部。我可以将它绝对定位到中间,但是当我改变浏览器大小时,img不会随之移动。我希望它自动放在窗口的中心。我很难过......?

我试过了,margin-right:auto;保证金左:自动。我也尝试过这样的技巧,你可以使保证金的左半部分宽度增加到前50%,但到目前为止还没有任何效果。

HTML:

    <body>
<div id="container">

<div id="header">
    <img id="logo-img" src="http://f.cl.ly/items/3c0h1b0F3t1D1S1T2J0F/smallersticker.png">
</div>
/*...(body div)
...(footer div)*/
</div> /*container*/

的CSS:

#header {

    background-color:transparent;
    height:260px;
    width:100%
}


#logo-img{
display: block;
    margin-left: auto;
    margin-right: auto;
}

另外,我还需要一个容器吗?不确定我是否需要javascript,或者是否可以使用html / css完成?希望有人可以帮忙,谢谢!

2 个答案:

答案 0 :(得分:0)

发生的事情是您已经正确地将图像居中。

你的问题是图像很大。如果您仔细观察,如果浏览器窗口的宽度小于图像,则图像不会居中。

从图像中删除白色区域,它将正确居中。

编辑:在IE中,您需要将规则text-align:center添加到#header

另一种方式:

如果您不想更改图片,可以使用此黑客:

    <style>
    #header {
        overflow-y: hidden;
        background-color: transparent;
        height: 260px;
        width: 100%;
        margin-left: 50%;
    }


    #logo-img{
        display: block;
        position: relative;
        right: 50%;
    }
    </style>
    <body>
    <div id="container">

    <div id="header">
        <img id="logo-img" src="http://f.cl.ly/items/3c0h1b0F3t1D1S1T2J0F/smallersticker.png">
    </div>
    /*...(body div)
    ...(footer div)*/
    </div> /*container*/

我刚刚学会了这个黑客here

答案 1 :(得分:0)

只需使用徽标大小为(like this here)的徽标,然后您需要做的就是将align =“center”属性添加到徽标的div中。