使元素彼此对齐

时间:2013-03-30 05:53:32

标签: html css

对于以下代码,它将图片呈现如下enter image description here 我想要的效果是“Hello,user1”与黑盒对齐,并且它们都与灰盒子的右侧对齐,我应该如何实现呢?

<html>
<head>
<style>
    #header {
    width: 100%;
    height: 81px;
    background: url(http://www5.picturepush.com/photo/a/12541848/img/Anonymous/header-bg.png) 0 0 repeat-x;
}
#header h1 {
    display: block;
    float: left;
    margin: 30px 0 0 35px;
    font-size: 18px;
    color: #6a6a6a;
}
#header #logo {
    display: block;
    float: left;
}
#header #userlog {
    width: 272px;
    height: 31px;
    background-color: #363636;
    border-radius: 2px;
    float: right;
    margin: 27px 26px 0 0;
}#header #userlog a {
    font-size: 13px;
    float: left;
    color: #b7b7b7;
    margin-top: 6px;
}

#welcome_msg {
    color: #b7b7b7;
    float: right;

}
    </style>

</head>
<body>
<div id="header">
    <a id="logo" href="dashboard.php"><img src="http://upload.wikimedia.org/wikipedia/commons/thumb/archive/c/c1/20070624012131!Fuji_apple.jpg/120px-Fuji_apple.jpg" alt="" /></a>
    <div class="welcome_msg" id="welcome_msg">hello, user1</div>
    <h1> My Portal   </h1>
    <div id="userlog">
        <a href="#" style="margin-left:25px;text-decoration:underline;">Contact Support</a>
        <a href="#" style="margin-left:20px;">FAQ</a>
        <a href="../index.php" style="margin-left:25px;">logout</a>
    </div>
</div>
</body>
</html>

2 个答案:

答案 0 :(得分:3)

将两个元素放入div并将该div向右浮动。右边的额外空间是因为元素的边距为26px。

<div id="whatever">
    <div class="welcome_msg" id="welcome_msg">hello, user1</div>
    <div id="userlog"> <a href="#" style="margin-left:25px;text-decoration:underline;">Contact Support</a>
        <a href="#" style="margin-left:20px;">FAQ</a>
        <a href="../index.php" style="margin-left:25px;">logout</a>
    </div>
</div>


#whatever {
    float:right;
}

#header #userlog {
    width: 272px;
    height: 31px;
    background-color: #363636;
    border-radius: 2px;
}

演示:http://jsfiddle.net/kzhuL/

答案 1 :(得分:0)

喜欢这个吗?

enter image description here

我添加了一个<div>容器来容纳#userlog#welcome_msg

<强> CSS

#header #userlog {
    margin: 0 26px 0 0;
}
#welcome_msg {
    margin-right:26px;
}

<强> HTML

<div id="container">
    <div class="welcome_msg" id="welcome_msg">hello, user1</div>
    <br />
    <div id="userlog"> 
        <a href="#" style="margin-left:25px;text-decoration:underline;">Contact Support</a>
        <a href="#" style="margin-left:20px;">FAQ</a>
        <a href="../index.php" style="margin-left:25px;">logout</a>
    </div>
</div>