如何在导航栏中将2个元素彼此相邻?

时间:2015-01-06 17:12:24

标签: html css

我已经做了很多环顾四周而且不能上班,我希望我的具体代码可以帮助我。 这是html:

<body>
<!-- <h3> Website Title </h3> -->
<ul id="navigationBarList">
  <li><a href="#About">About</a></li>
  <li><a href="#Bookings">Bookings</a></li>
  <li><a href="#Blog">Blog</a></li>
  <li><a href="#Pricing">Pricing</a></li>
</ul>

<div id="element2"> Sign in </div>



</body>

这是css:

#navigationBarList{
    display: inline-block;
    margin: 0;
    margin-right: 10px;
    padding: 10px;
    background-color: black;    
    font-size: 25px;
    color: red;
    width: 100%;
}
#navigationBarList li{
    display: inline;
    width: 100px;
    margin-right: 20px;
}
#element2{
    display: inline;
    width: 100px;
    background-color: red;
}

并且我希望登录链接与列表项位于同一行。 (我没有将它列入列表的原因是我希望列表在每个元素之间具有相等的空间然后更宽的间隙与登录按钮推到屏幕的右边但是无法解决这个问题我应该将它们分开)

到目前为止,这段代码只是把它推到了

之下

1 个答案:

答案 0 :(得分:1)

您需要添加float: right添加到#element2并从width: 100%;删除#navigationBarList,然后将font-size: 25px;添加到#element2

#navigationBarList{
    display: inline-block;
    margin: 0;
    background-color: black;    
    font-size: 25px;
    color: red;
}
#navigationBarList li{
    display: inline;
    width: 100px;
    margin-right: 20px;
}
#element2{
    display: inline;
    float: right;
    font-size: 25px;
    background-color: red;
}
<body>
<!-- <h3> Website Title </h3> -->
<ul id="navigationBarList">
  <li><a href="#About">About</a></li>
  <li><a href="#Bookings">Bookings</a></li>
  <li><a href="#Blog">Blog</a></li>
  <li><a href="#Pricing">Pricing</a></li>
</ul>

<div id="element2"> Sign in </div>



</body>

更清洁的方法可能看起来像这样

#navigationBarList{
    margin: 0;
    padding: 0
    /*
    display: inline-block; 
    margin: 0;
    margin-right: 10px; add this to the list
    padding: 10px; add this to anchors
    background-color: black; add this to the list    
    font-size: 25px; you can add this to #element2,#navigationBarList
    color: red;  add this to anchors
    width: 100%; you don't need this
    */
}
#navigationBarList li{
    float: left;
    list-style: none;
    background-color: black
}
#navigationBarList a{
    margin-right: 10px;
    color: red;
    padding: 20px;
}
#element2{
    float: right;
    background-color: red;
}
#element2,#navigationBarList{
    font-size: 25px;
    display: inline-block;
}
<!-- <h3> Website Title </h3> -->
<ul id="navigationBarList">
  <li><a href="#About">About</a></li>
  <li><a href="#Bookings">Bookings</a></li>
  <li><a href="#Blog">Blog</a></li>
  <li><a href="#Pricing">Pricing</a></li>
</ul>

<div id="element2"> Sign in </div>