我创建了一个标题,其中一个div作为网站的主菜单,并在其中添加了一些div作为主菜单项。我的问题是:如何将内部div垂直和水平居中对齐,这些div是放置在主菜单项中的主菜单的标题?我尝试了许多解决方案,例如转换和显示的flex风格,但不幸的是,没有任何效果。为什么CSS中没有XAML中的Horizo​​ntal / VerticalAlignment之类的东西?



body {
  margin: 0;
}

header {
  height: 50px;
  background-color: lightgrey;
}

#main-menu {
  margin: 0 auto;
  width: 1000px;
  height: inherit;
}

.main-menu-item {
  float: left;
  width: 100px;
  height: inherit;
}

.main-menu-header {
  display: block;
  height: inherit;
}

.main-submenu {
  width: inherit;
  word-wrap: break-word;
  /*display: none;*/
  list-style: none;
  margin-left: -40px;
  margin-top: 0px;
}

<body>
  <header>
    <div id="main-menu">
      <div class="main-menu-item" onmouseover="ChangeDisplayOfSelectedSubmenu(0, 'block')" onmouseout="ChangeDisplayOfSelectedSubmenu(0, 'none')">
        <div class="main-menu-header">MenuItem1</div>
        <ul class="main-submenu">
          <li>SubMenuItem1</li>
          <li>SubMenuItem2</li>
          <li>SubMenuItem3</li>
        </ul>
      </div>

      <div class="main-menu-item" onmouseover="ChangeDisplayOfSelectedSubmenu(1, 'block')" onmouseout="ChangeDisplayOfSelectedSubmenu(1, 'none')">
        <div class="main-menu-header">MenuItem2</div>
        <ul class="main-submenu">
          <li>SubMenuItem1</li>
          <li>SubMenuItem2</li>
          <li>SubMenuItem3</li>
        </ul>
      </div>

      <div class="main-menu-item" onmouseover="ChangeDisplayOfSelectedSubmenu(2, 'block')" onmouseout="ChangeDisplayOfSelectedSubmenu(2, 'none')">
        <div class="main-menu-header">MenuItem3</div>
        <ul class="main-submenu">
          <li>SubMenuItem1</li>
          <li>SubMenuItem2</li>
          <li>SubMenuItem3</li>
        </ul>
      </div>
    </div>
  </header>

最佳答案

简单地使用填充顶部和填充底部?
尝试CSS line-height属性,请遵循以下步骤:https://www.w3schools.com/cssref/pr_dim_line-height.asp
您可以使用CSS旧技巧,使用此方法:

header{
    height:50px;
    display:block;
}

#main-menu{
    position:aboslute;
    top:50px;
    margin-top:-25px;
}

09-20 09:44