Search code examples
csslistmenusubmenu

CSS - Horizontally style list without using absolute positioning and JS


Is it possible to create a horisontally styled menu (like on image below) without using absolute positioning or JS?

Trying to create a menu. It uses standard unordered list to display.

Here is what I'm trying to achieve:

After

(Green list is a submenu of "How are you". It has a line break because it is limited by width.)

And currently what I have is this:

Before

This is the pen: http://codepen.io/olegovk/pen/NNREMY

And the code:

HTML

<nav>
  <ul>
    <li><a href="#">Hello</a></li>
    <li><a href="#">How are you</a>
      <ul>
        <li><a href="#">Allright!</a></li>
        <li><a href="#">And you?</a></li>
        <li><a href="#">Fine</a></li>
        <li><a href="#">La-la-la</a></li>
        <li><a href="#">Bla-bla-bla</a></li>
        <li><a href="#">Cheerio!</a></li>
      </ul>
    </li>
    <li><a href="#">Good bye</a></li>
  </ul>
</nav>
<div class="clear"></div>
<p>Some paragraph to make sure it's below the menu.</p>

CSS

.clear {
  clear: both;
}
p {
  background-color: lightgrey;
}
li {
  float: left;
  list-style: none;
  display: list-item;
  margin: 0 0.5em;
}
li li {
  margin: 0 1em;
}
li li a {
  color: green;
}
nav ul ul{
  max-width: 300px;
}

I know it's possible with absolutely positioning child lists or with JS. But absolute positioning of child lists takes them out of doc flow. As a result they overlap with content below them. Also I can't use JS.


Solution

  • Seems that it's impossible.

    Here is another similar question: Position: absolute and parent height?

    With regards to the menu, to achieve the desired result, the only solution is to have top level menu and sub-menu in different lists. That way no need to position sub-menu (second level list) absolutely.