Vic T Vic T - 6 months ago 16
HTML Question

Expand absolute div to relative child auto width

So, I've got a sub menu

ul
item, which I need to expand to the auto
width
of the widest child
li
, without specifying actual
width
. As of right now, child ul is taking the width of .mainlink and text inside li items starts collapsing. I need it to be in one line and go beyond .mainlink width if necessary.

I've tried all the possible
display
s, but can't get it to work.



.mainnav {
display: table;
table-layout: fixed;
}
ul.mainnav li {
display: table-cell;
}
.subnav {
position: absolute;
top: 40px;
}
.menuitem {
position: relative;
display: block;
}

<ul class="mainnav">
<li class="mainlink"><a href="">Link 11</a>
</li>
<li class="mainlink">
<a href="">Link 12</a>
<ul class="subnav">
<li class="menuitem"><a href="">link 1</a>
</li>
<li class="menuitem"><a href="">link 2</a>
</li>
</ul>
</li>
</ul>




Answer

reset padding on .subnav because ul has padding by default

UPDATE (based on OP updated question)

use display:inline-block in .mainnav > li


.mainnav {
  background:lightyellow;
  position:relative
}
ul.mainnav > li {
  display: inline-block;
  background:lightblue;
}
.subnav {
  position: absolute;
  top: 40px;
  padding: 0;
  border: 5px solid green
}
.menuitem {
  position: relative;
  display: block;
  background: red
}
<ul class="mainnav">
  <li class="mainlink"><a href=" ">Link 11</a></li>
   <li class="mainlink">
    <a href="">Link 12</a>
    <ul class="subnav">
      <li class="menuitem"><a href="">link 1</a>
      </li>
      <li class="menuitem"><a href="">link 2 long text</a>
      </li>
    </ul>
  </li>
</ul>