【问题标题】:How to auto center an img inside a div regardless of browser window size?无论浏览器窗口大小如何,如何在 div 内自动居中 img?
【发布时间】:2012-11-09 06:34:02
【问题描述】:

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

我试过了,margin-right:auto;左边距:自动。我也尝试过让 margin-left 负一半宽度和顶部 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 来完成?希望有人能帮忙,谢谢!

【问题讨论】:

    标签: window size image center


    【解决方案1】:

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

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

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

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

    另一种方式:

    如果您不想更改图像,可以使用此 hack:

        <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

    【讨论】:

    • 等等,我在登录 IE 之前已经回复了。在 IE7 中它不居中。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2014-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-19
      • 1970-01-01
      • 2018-01-12
      • 2021-02-13
      • 1970-01-01
      相关资源
      最近更新 更多