2017-04-07 29 views
1

我希望鏈接也vertical-aligned: middle;旁邊的<h1>元素。 但這是不可能的,因爲導航由於某種原因被推下來。 我檢查過了,沒有保證金或填充。導航被推下固定格

的jsfiddle:https://jsfiddle.net/dak3up0m/

<div class="fixed"> 
    <h1> 
    Title 
    </h1> 

    <nav> 
    <ul> 
     <li> 
     <a href="#">link1</a> 
     </li> 
     <li> 
     <a href="#">link2</a> 
     </li> 
    </ul> 
    </nav> 
</div> 

.fixed 
{ 
    width: 100%; 
    height: 100px; 
    background-color:red; 
} 

h1 
{ 
    height: 100px; 
    line-height: 100px; 
    display:inline-block; 
    margin:0; 

    color:white; 
} 

nav 
{ 
    position:relative; 
    height:100%; 
    width: auto; 
    display:inline-block; 
    background-color:green; 

    top:0; 
    right:0; 

    > ul 
    { 
     height:auto; 

     > li 
     { 
      font-size: 15px; 
      padding: 0 12px; 
      text-align:center; 
      line-height: inherit; 
      display:inline-block; 


      &:not(:last-child) 
      { 
       margin-right:0; 
      } 

      button 
      { 
       padding: 0; 

       &:hover 
       { 
       background-color: inherit; 
       border:none; 
       } 
      } 

      a 
      { 
       line-height: 50px; 
      } 
     } 
    } 
} 
+0

正如你已經兩個導航和H1爲inline-block的元素,你需要將相同的垂直對準他們,使他們排隊​​:https://開頭的jsfiddle .net/dak3up0m/4 /或者如果你想讓li居中:https://jsfiddle.net/dak3up0m/13/ – Pete

+0

check [this](https://jsfiddle.net/dak3up0m/26/) – Alex

回答

2

給資產淨值高度:100像素;那麼無論你想垂直對齊給它的行高:100px;

https://jsfiddle.net/dak3up0m/14/

否則,我只想改變你的整個結構和使用Flexbox的,更清潔和更容易檢查出來:

.fixed { 
    display: flex; 
    align-items: center; 
    height: 100px; 
    background-color: tomato; 

    h1 { 
    margin: 0; 
    } 
} 

nav ul { 
    display: flex; 
    align-items: center; 
    margin: 0; 
    padding: 0; 
    list-style-type: none; 

    li { 
    margin-left: 10px; 
    } 
} 

https://jsfiddle.net/dak3up0m/23/

1

我覺得一個很優雅的解決方案是這樣的一個使用flexbox。一般來說,當您嘗試將多個元素垂直居中時,這是最簡單和最佳的性能方式。此外,代碼更乾淨。

看到這個fiddle

.fixed 
{ 
    width: 100%; 
    height: 100px; 
    background-color:red; 
    display:flex; 
} 

h1 
{ 
    height: 100px; 
    display:flex; 
    align-items:center; 
    margin:0 10px; 
    color:white; 
} 

nav 
{ 
    position:relative; 
    height:100%; 
    width: auto; 
    display:flex; 
    align-items:center; 
    justify-content:space-around; 
    background-color:green; 

    top:0; 
    right:0; 

    > ul 
    { 
     height:auto; 
     padding: 0px 40px; 
     > li 
     { 
      font-size: 15px; 
      padding: 0 12px; 
      text-align:center; 
      line-height: inherit; 
      display:inline-block; 


      &:not(:last-child) 
      { 
       margin-right:0; 
      } 

      button 
      { 
       padding: 0; 

       &:hover 
       { 
       background-color: inherit; 
       border:none; 
       } 
      } 

      a 
      { 
       line-height: 50px; 
      } 
     } 
    } 
}