div不显示在页面中心

时间:2013-05-16 00:27:52

标签: html css

我有这个css代码:

#header-topbar {
    width:100%;
    height:120px;
    padding-top:5px;
}
#header-right-content {
    float:right;
    margin-right:14%;
    margin-top:20px;
    font-size:20px;
    text-align:right;
    color:#000000;
}
#logo {
    position: absolute;
    float: left;
    margin-left: 15%;
    margin-top: 25px;
    width: 360px;
    height: 50px;
    border:1px solid black;
}
#logo-small {
    display:none;
}

然后这是我的响应式CSS:

@media screen and (max-width: 780px) {
    #header-right-content {
            display:none;
    }
    #logo {
        display:block;
        float: left;
        margin-top: 25px;
        width: 360px;
        height: 50px;
        border:1px solid black;
    }
}

然后是HTML:

<div id="header-topbar">
<div id="logo"><img src="images/logo.png" width="360" height="50" /></div>
<div id="header-right-content"><?php
if($_SESSION["customer_loggedin"] == 'yes')
{
    echo 'Hello '.$_SESSION["customer_forename"].' '.$_SESSION["customer_surname"].' | <a href="/customer/index.php">Customer Centre</a> | <a href="/customer/logout.php">Logout</a>';
}
else
{
    echo '<a href="/customer/login.php">Customer Login</a>';
}
?><br /><br />
Tel: <?php echo $main_phone_number; ?><br />Email: <?php echo $company_emailaddress_sales; ?></div> <!-- header-right-content -->
</div>

由于某种原因,随着屏幕变小,我无法将徽标显示在页面中央。 div #logo不会居中在页面中。

任何可能导致这种情况的想法?

2 个答案:

答案 0 :(得分:2)

由于您使用的是绝对定位div,因此使用left和margin-left来居中:

@media screen and (max-width: 780px) {
    #header-right-content {
        display:none;
    }
    #logo {
        display:block;
        float: left;
        margin-top: 25px;
        width: 360px;
        height: 50px;
        border:1px solid black;
        left: 50%; //this centers the left side of the div to the page
        margin-left: -180px; //this subtracts half the width to center it on the page
    }
}

答案 1 :(得分:0)

float:left;正是如此。它将元素浮动到左侧。您希望<img>标记位于#logo元素中心,还是#logo元素居中于其父元素中?

如果您想将div元素居中,请使用margin: 0 auto;

#logo {
  position: absolute;
  float: left;
  margin-left: 25px auto 0;
  width: 360px;
  height: 50px;
  border:1px solid black;
}

此外,这是一个非常标准的做法和简单的解决方案,您应该能够自己找到,即使在这个被无数次询问过的网站上也是如此。我不会在这样的问题上标记人,但是这个网站上的很多人都会这样。太多标志会让您不再提出问题,因此请务必在此处发布问题之前仔细研究。

相关问题