CSS Flex拉伸不与垂直对齐一起使用

时间:2017-12-03 14:27:40

标签: css css3 flexbox

我正在使用CSS flexbox创建一个简单的菜单栏。我的菜单按钮使用stretch,因此按钮与菜单栏的高度相同。

问题是,如果其中一个div高于其他div,则按钮内的文本不会垂直居中。

我尝试过使用align-items:centerjustify-content:center。虽然内容的中心,按钮不再伸展到与其父母相同的高度,当鼠标悬停在div上时看起来很难看:(

我的弹性儿童可以垂直伸展并使其内容垂直居中吗?

HTML

<nav>
    <div><img src="./largelogo.png"></div>      // a tall div
    <div>Artists</div>                          // should stretch AND center
    <div>Playlists</div>
    <div>Genres</div>
</nav>

CSS

nav {
  display: flex;
  align-items: stretch;
  justify-content: center;
  background: #60B99A;
  color:white;
}

nav div:hover {
    color: #60B99A;
    background: white;
}

1 个答案:

答案 0 :(得分:1)

如果您还将内部div设为灵活容器,则可以将其文本/内容垂直居中。

Stack snippet

&#13;
&#13;
nav {
  display: flex;
  /*align-items: stretch;              stretch is default, so this is not needed  */
  justify-content: center;
  background: #60B99A;
  color:white;
}

nav div {
  display: flex;                   /*  added  */
  align-items: center;             /*  added  */
}

nav div:hover {
  color: #60B99A;
  background: white;
}

nav div img {
  display: block;                  /*  remove the bottom white space  */
}
&#13;
<nav>
    <div><img src="http://placehold.it/100x150/f00"></div>      
    <div>Artists</div>                          
    <div>Playlists</div>
    <div>Genres</div>
</nav>
&#13;
&#13;
&#13;

对于希望内部div本身居中的任何人,请使用align-items: center

Stack snippet

&#13;
&#13;
nav {
  display: flex;
  align-items: center;             /*  changed  */
  justify-content: center;
  background: #60B99A;
  color:white;
}

nav div:hover {
    color: #60B99A;
    background: white;
}

nav div img {
  display: block;                  /*  remove the bottom white space  */
}
&#13;
<nav>
    <div><img src="http://placehold.it/100x150/f00"></div>      
    <div>Artists</div>                          
    <div>Playlists</div>
    <div>Genres</div>
</nav>
&#13;
&#13;
&#13;

相关问题