如何在导航栏中垂直居中放置元素和文本

卡兰·威尔斯(Karan Wales):

嗨,我刚开始学习Web开发,有人可以帮助我。我希望所有子元素和带有子元素的文本垂直居于父div的中心。

将会在页面右侧添加另外150px的图标,但稍后会进行说明。

我面临着li&a从ul溢出的各种问题,无法设置ul的高度

body {
  margin: 0;
  padding: 0;
}

.header {
  width: 100%;
  height: 100px;
  background-color: #18269e;
  display: flex;
  align-items: center;
}

.header-bar {
  width: 800px;
  height: 100px;
}

h1 {
  font-size: 22px;
  color: #e1e1e1;
  character-spacing: 0.6;
}

span {
  color: #de893f;
}

.header-bar ul {
  list-style: none;
  /*   align-items:center; */
  /*   height: 100px; */
  overflow: auto;
}

li {
  display: inline;
  width: 150px;
  float: left;
  /*   font-size: 20px; */
  text-align: center;
}

a {
  /*   font-size: 20px; */
  color: #e1e1e1;
  width: 120px;
  display: block;
  text-decoration: none;
  margin: 0 15px;
}
<div class='header'>
  <h1>Testing <span>Website</span></h1>
  <div class='header-bar'>
    <ul>
      <li><a href='#'>Home</a></li>
      <li><a href='#'>Projects</a></li>
      <li><a href='#'>Gallery</a></li>
      <li><a href='#'>Contact Us</a></li>
      <li><a href='#'>Testing</a></li>
    </ul>
  </div>
</div>

甘:

使右侧链接垂直居中的最快方法是添加display:flex和'align-items:center to the.header-bar`元素。请参阅下面的更新示例。

有关在此处使用flex居中的更多信息:https : //developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Aligning_Items_in_a_Flex_Container

body {
  margin: 0;
  padding: 0;
}

.header {
  width: 100%;
  height: 100px;
  background-color: #18269e;
  display: flex;
  align-items: center;
}

.header-bar {
  width: 800px;
  height: 100px;
  display: flex; /* all elements inside will follow flex display */
  align-items: center; /* all children will vertically center */
}

h1 {
  font-size: 22px;
  color: #e1e1e1;
  character-spacing: 0.6;
}

span {
  color: #de893f;
}

.header-bar ul {
  list-style: none;
  /*   align-items:center; */
  /*   height: 100px; */
  overflow: auto;
}

li {
  display: inline;
  width: 150px;
  float: left;
  /*   font-size: 20px; */
  text-align: center;
}

a {
  /*   font-size: 20px; */
  color: #e1e1e1;
  width: 120px;
  display: block;
  text-decoration: none;
  margin: 0 15px;
}
<div class='header'>
  <h1>Testing <span>Website</span></h1>
  <div class='header-bar'>
    <ul>
      <li><a href='#'>Home</a></li>
      <li><a href='#'>Projects</a></li>
      <li><a href='#'>Gallery</a></li>
      <li><a href='#'>Contact Us</a></li>
      <li><a href='#'>Testing</a></li>
    </ul>
  </div>
</div>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章