我向右浮动search_and_avatar div,并使用displayvertical-align属性将其与父容器的中间对齐。但是它位于底部。这是为什么?

这是fiddle中的完整代码

HTML:

<header>
    <h1>CSS-Tricks</h1>
    <nav id="main_nav">
        <ul>
            <li><a href="index.html">Blog</a></li>
        </ul>
    </nav>

    <div id="search_and_avatar">
    <form action="index.html" method="post" id="search_form">
      <input type="text" id="search" name="search">
    </form>
    <img src="images/avatar.png">
    </div>
</header>


CSS:

header {
    background-color:#151515;
    overflow:hidden;
    height: 100px;
}

header h1, img, #search_form {
    float:left;
}

#main_nav a {
    color:#FFF;
    text-decoration:none;
}



header img {
    width:35px;
    display: table-cell;
    vertical-align: middle;
}

#search_and_avatar {
    display: flex;
    justify-content: flex-end;
    flex: 1;
    display: table;
    display: table-row;
    float:right;
}

header form {
    text-align:right;
    display: table-cell;
    vertical-align: middle;
}

最佳答案

header中添加了flex属性



body {
  margin:0;
  font-family: 'Source Sans Pro', sans-serif;
}

ul {
  padding:0;
}

header {
  background-color:#151515;
  overflow:hidden;
  height: 100px;
  display:flex;
  flex:1 1 0;
  align-items: center;
  justify-content: center;
}

h1 {
  color:#FFF;
  font-family: "Arial Rounded MT", "Helvetica Rounded", Arial, sans-serif;
  font-size: 40px;
  font-weight: normal;
  line-height:25px;
  padding: 10px 20px 0px;
  flex: 1;
}

#main_nav a {
  color:#FFF;
  text-decoration:none;
}

#main_nav {
  display: table;
  text-align:center;
  margin:0px auto;
}

#main_nav ul {
  display: table-row;
}

#main_nav ul li {
  padding: 15px;
  display: table-cell;
  vertical-align: middle;
  top: 50%;
  display:inline;
}

header img {
  width:35px;
  display: inline-block;
  vertical-align: middle;
}

#search_and_avatar {
  /*display: flex;
  justify-content: flex-end;
  flex: 1;
  display: table;
  display: table-row;
  float:right;*/
}

header form {
  text-align:right;
  display:inline-block;
  vertical-align: middle;
}

<div id="wrapper">
  <header>
    <h1>CSS-Tricks</h1>
    <nav id="main_nav">
      <ul>
        <li><a href="index.html">Blog</a></li>
        <li><a href="video_screencasts.html">Videos</a></li>
        <li><a href="almanac.html">Almanac</a></li>
        <li><a href="snippets.html">Snippets</a></li>
        <li><a href="forums.html">Forums</a></li>
        <li><a href="shop.html">Shop</a></li>
        <li><a href="lodge.html">Lodge</a></li>
        <li><a href="jobs.html">Jobs</a></li>
      </ul>
    </nav>

    <div id="search_and_avatar">
      <form action="index.html" method="post" id="search_form">
        <input type="text" id="search" name="search">
      </form>
      <img src="images/avatar.png">
    </div>
    <!--
<ul id="account_nav">
<li><a href="login.html">Log In</a></li>
<li><a href="signup.html">Sign Up</a></li>
</ul>
-->
  </header>
</div>





这是小提琴Demo

10-04 16:49