Kuba Krzyżyński Kuba Krzyżyński - 1 month ago 18
CSS Question

Submenu placement HTML

I made my submenu appear when I hover over one option in menu. However when I do it it extends menu height (PIC1). I tried setting menu height on 56px and then it doesn't extend but it ruins my whole layout (PIC2). I also tried putting position:absolute in empty div between menu_option and submenu but then submenu changes sizes and loses attributes (PIC3).

HTML:

<div id="menu">
<div class="menu_option">Strona główna</div>
<div class="menu_option">Galeria</div>
<div class="menu_option">Reżyserzy
<div>
<div class="submenu" style="margin-top:10px">Quentin Tarantino</div>
<div class="submenu">Bracia Coen</div>
<div class="submenu">Wes Anderson</div>
</div>
</div>
<div class="menu_option">Ulubione filmy</div>
<div class="menu_option">Seriale</div>
<div class="menu_option">Kontakt</div>
<div style="clear:both"></div>
</div>


CSS:

#menu
{
margin-bottom:20px;
background-color:#73818c;
padding:10px;
}
.menu_option
{
float:left;
min-width:100px;
text-align:center;
border-right:dotted 2px black;
padding:10px;
font-size:16px;
}
.submenu
{
text-align:center;
border-bottom:dotted 2px black;
padding-top:10px;
padding-bottom:10px;
display:none;
font-size:13px;
}
.submenu:hover
{
background-color:white;
}
.menu_option:hover div
{
display:block;
}
.menu_option:hover
{
background-color:lightgray;
cursor:pointer;
}

Answer

Setting position: absolute on the div that holds the submenus (and position: relative on the menu options) will keep the height of that div (and its contents) from affecting the height of its parent elements.

#menu {
  margin-bottom: 20px;
  background-color: #73818c;
  padding: 10px;
}

 #menu, #menu * {
    box-sizing: border-box;
  }

.menu_option {
  float: left;
  min-width: 100px;
  text-align: center;
  border-right: dotted 2px black;
  padding: 10px;
  font-size: 16px;
  position: relative;
}

/* I've added this class to the div around the .submenus */
.submenu_wrapper {
  position: absolute;
  background: lightgray;
  left: 0;
  right: 0;
  }

.submenu {
  text-align: center;
  border-bottom: dotted 2px black;
  padding-top: 10px;
  padding-bottom: 10px;
  display: none;
  font-size: 13px;
}
.submenu:hover {
  background-color: white;
}
.menu_option:hover div {
  display: block;
}
.menu_option:hover {
  background-color: lightgray;
  cursor: pointer;
}
<div id="menu">
  <div class="menu_option">Strona główna</div>
  <div class="menu_option">Galeria</div>
  <div class="menu_option">Reżyserzy
    <div class="submenu_wrapper"> <!-- new class -->
      <div class="submenu" style="margin-top:10px">Quentin Tarantino</div>
      <div class="submenu">Bracia Coen</div>
      <div class="submenu">Wes Anderson</div>
    </div>
  </div>
  <div class="menu_option">Ulubione filmy</div>
  <div class="menu_option">Seriale</div>
  <div class="menu_option">Kontakt</div>
  <div style="clear:both"></div>
</div>