2017-04-07 67 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; 
      } 
     } 
    } 
}