Center sub menu absolute with css

0

Good afternoon. I would like to know how to center my sub menu for the main menu. The sub menu records are dynamic, so I can not give a margin-left: -px because I do not know the size that will be my sub-menu ...

Here is an example code for my problem:

ul, li {
  margin : 0;
  padding : 0;
}

#menu {
  width : 100%;
}

#menu li {
  margin : 0;
  list-style: none;
}

#menu > li {
  display : inline-block;
  border : 1px solid #000000;
  cursor : pointer;
}

#menu > li:hover ul {
  display : block;
}

#menu li ul {
  display : none;
  position : absolute;
  background-color : #000000;
  color : #FFFFFF;
}

#menu li ul li:hover {
  background-color : #d2d2d2;
}
<ul id="menu">
  <li>Menu 1</li>
  <li>
    Menu 2
    <ul>
      <li>Sub menu 1</li>
      <li>Sub menu 2</li>
      <li>Um subMenu que é mais longo</li>
    </ul>
   </li>
  <li>Menu 3</li>
</ul>
    
asked by anonymous 02.08.2016 / 22:54

1 answer

1

This solution is too complex for CSS. We'll have to use JavaScript to calculate the correct placement of the submenus:

$( function() {
  // Armazenamos o submenu numa variável por conveniência
  var $submenu = $( ".submenu" );

  $submenu.each(function(){
	$(this).css( "left", ( $(this).parent().outerWidth() / 2 ) - (                $(this).width() / 2 ) );
});

  // Aqui, mudamos a propriedade left para ser igual ao tamanho do pai do submenu / 2 (seu centro) - a largura do submenu, em si, dividido por dois também
  $submenu.css( "left", ( $submenu.parent().outerWidth() / 2 ) - ( $submenu.width() / 2 ) );
} );
* {
  font-family: sans-serif;
}

ul, li {
  margin : 0;
  padding : 0;
}

#menu {
  width : 100%;
}

#menu li {
  margin : 0;
  list-style: none;
}

#menu > li {
  display : inline-block;
  border : 1px solid #000000;
  cursor : pointer;
}

#menu > li:hover ul {
  display : block;
}

#menu li ul {
  display : none;
  position : absolute;
  background-color : #000000;
  color : #FFFFFF;
}

#menu li ul li:hover {
  background-color : #d2d2d2;
}

/* Regras novas */
.wrapper-menu {
  width: 100%;
  text-align: center;
}
#menu .has-submenu {
  position: relative;
}

#menu .submenu li {
  white-space: nowrap;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><divclass="wrapper-menu">
  <ul id="menu">
  <li class="has-submenu">
    Menu 1
    <ul class="submenu">
      <li>Sub menu 1</li>
      <li>Sub menu 2</li>
      <li>Um subMenu que é mais longo</li>
    </ul>
  </li>
  <!-- Criamos classes para melhor controle -->
  <li class="has-submenu">
    Menu 2
    <ul class="submenu">
      <li>Sub menu 1</li>
      <li>Sub menu 2</li>
      <li>Um subMenu que é mais longo</li>
    </ul>
   </li>
  <li>Menu 3</li>
</ul>
</div>
    
03.08.2016 / 02:19