oli.G
oli.G

Reputation: 1350

Floating inside an absolute-positioned div, placed inside a relative positioned element

I'm creating a pure-CSS hover dropdown menu, based on a very basic idea idea.

The HTML:

<ul id="top">
  <li>
    <a href="#">Menu item 1</a></li>
  <li>
    <a href="#">This one has submenu</a>
    <div class="submenu">
      <ul>...</ul>
    <div>
  </li>
</ul>

The CSS:

div.submenu { 
  display: none; 
  position: absolute;
}
ul#top > li:hover div.submenu { display:block; }

As far as I know, this is the bare minimum to get the idea working. The problem is I want the submenu to be multi-column, without actually using CSS3 multiple columns.

So I decided to break my submenu into multiple lists and have them float: left like this:

<ul id="top">
  <li>
    <a href="#">Menu item 1</a></li>
  <li>
    <a href="#">This one has submenu</a>
    <div class="submenu">
      <ul>...</ul>
      <ul>...</ul>
      <ul>...</ul>
    <div>
  </li>
</ul>

...and the CSS:

div.submenu ul { float:left; }

This worked well until the point when I got a pretty big submenu in the last main menu item, producing a result like this:

The problem is it is unacceptable to have the submenu fall outside the container. I decided to mark the second half of the main menu items as class="right", and align the submenu's right border to the parent item's right border.

li.right div.submenu { right: 0; }
/* this placed the submenu to the right of the entire page;
it needs a positioning context: */

ul#top li { position:relative; }

That last line causes the <ul>'s to stop floating and just get stacked on top of each other.

Is there a way to keep them floating without setting the <div class="submenu"> to a fixed width?

Interactive demo: http://codepen.io/oli-g-sk/pen/ociet

Edit: if this helps somehow, it is allowed to set the submenu list items .submenu > ul > li to a fixed width. In fact I'm already doing it in the demo.

Upvotes: 3

Views: 960

Answers (1)

Bodzio
Bodzio

Reputation: 2520

Try removing float:left from div.submenu ul and add these two rules:

div.submenu {
    white-space: nowrap;
}

div.submenu ul {
    /* float:left; <-- remove this */
    display: inline-block;
}

demo: http://codepen.io/anon/pen/ApxFd

Upvotes: 1

Related Questions