下拉菜单子菜单的居中

时间:2019-02-18 09:44:35

标签: css

我正在为下拉菜单改编css样式表。我在将子菜单的框居中时遇到麻烦。当前看起来像this

#nav{
  list-style:none;
  margin:0;
  padding:120px 100px;
  text-align:center;
}
#nav li{
  position:relative;
  display:inline;
}
#nav a{
  display:inline-block;
  padding:10px;
}
#nav ul{
  position:absolute;
  left:-9999px;
  margin:0;
  padding:0;
  text-align:center;
}
#nav ul li{
  display:block;
}
#nav li:hover ul{
  left:0;
}
#nav li:hover a{
}
#nav li:hover ul a{
  text-decoration:none;
  background:none;
}
#nav li:hover ul a:hover{
  background:#fff;
}
#nav ul a{
  white-space:nowrap;
  display:block;
}
a{
  color:#c00;
  text-decoration:none;
  font-weight:bold;
}
a:hover{
}

但是我希望子框相对于较高级别的框居中。我该如何实现?

1 个答案:

答案 0 :(得分:1)

  • li立即(顶层)放入相对容器
  • 左位置将ul嵌套50%到新定义的相对容器中,并对其-50%进行大小转换
  • 删除嵌套left:-9999px;上的ul并切换display: none / block

#nav > li {
  position: relative;
}

#nav {
  list-style: none;
  margin: 0;
  padding: 20px 100px;
  text-align: center;
}

#nav li {
  position: relative;
  display: inline;
}

#nav a {
  display: inline-block;
  padding: 10px;
}

#nav ul {
  display: none;
  position: absolute;
  margin: 0;
  padding: 0;
  left: 50%;  
  transform: translateX(-50%);
}

#nav ul li {
  display: block;
}

#nav li:hover ul {
  display: block;
}

#nav li:hover a {}

#nav li:hover ul a {
  text-decoration: none;
  background: none;
}

#nav li:hover ul a:hover {
  background: #fff;
}

#nav ul a {
  white-space: nowrap;
  display: block;
}

a {
  color: #c00;
  text-decoration: none;
  font-weight: bold;
}
<ul id="nav">
  <li><a href="#">One</a>
    <ul>
      <li><a href="#">Sub One</a></li>
      <li><a href="#">Sub Two</a></li>
    </ul>
  </li>
  <li><a href="#">Two</a>
    <ul>
      <li><a href="#">Sub One</a></li>
      <li><a href="#">Sub Two</a></li>
    </ul>
  </li>
  <li><a href="#">Three</a>
    <ul>
      <li><a href="#">Sub One</a></li>
      <li><a href="#">Sub Two</a></li>
    </ul>
  </li>
</ul>

jsFiddle