Saraha
Saraha

Reputation: 146

Centering of dropdown-menu submenus

I was adapting a css stylesheet for a dropdown-menu. I am having troubles with centering the boxes for the sub-menu. It currently looks like 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{
}

But I would like that the sub-boxes are centered with respect to the box on the higher level. How Can I achieve that?

Upvotes: 1

Views: 100

Answers (1)

Andy Hoffman
Andy Hoffman

Reputation: 19109

  • Make immediate (top level) lis into relative containers
  • Left position nested uls 50% within the newly-defined relative container and translate them -50% of their own size
  • Remove left:-9999px; on nested uls and toggle 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

Upvotes: 1

Related Questions