html – Broken menu due to one symbol

Question:

Hello everyone! Yesterday I faced such a problem that my layout broke, for a long time I could not understand why, I dug and dug and finally got to the bottom of the truth and was able to reproduce it. I have a horizontal dropdown menu. But in some cases, drop-down submenus appear to the right of the block you are hovering over, and not below.

I will be very grateful if someone can explain why this is happening at all. Below are 2 examples with code: a good option and a bad option.

The layout is being repaired because I added a newline character (or any other character) between the a and ul elements. For me, this behavior is very incomprehensible and I would like to figure out how to avoid such situations.

.menu {
  text-align: center;
}

.menu ul {
  display: inline-block;
  margin: 0;
  padding: 0;
  list-style: none;
}

.menu ul:after {
  content: '';
  display: table;
  clear: both;
}

.menu > ul > li {
  text-align: left;
  float: left;
  position: relative;
}

.menu li ul {
  position: absolute;
  visibility: hidden;
  opacity: 0; 
}

.menu li ul li {
  position: relative;
}

.menu li:hover > ul {
  visibility: visible;
  opacity: 1;
}
Хороший вариант:

<div class="menu">
  <ul>
    <li><a href="">Пункт 1-1</a>
      <ul>
        <li><a href="">Пункт 2-1</a></li>
      </ul>
    </li>
  </ul>
</div>

Плохой вариант:

<div class="menu">
  <ul>
    <li><a href="">Пункт 1-1</a><!--
      --><ul>
        <li><a href="">Пункт 2-1</a></li>
      </ul>
    </li>
  </ul>
</div>

UPDATE # 1

I checked this code in a couple of browsers:

  1. Google Chrome 63.0.3239.84 : good option is submenu at the bottom, bad option is submenu on the right.
  2. Firefox 57.0.2 : Both options are submenu on the right.
  3. Internet Explorer 11.726.15063.0 : Both options are submenu on the right.

Answer:

I dug even deeper. Understood. The problem was that the .menu ul element .menu ul display: inline-block (needed for correct centering, using text-align: center ). I fixed this problem by changing the centering method.

The following example works in all the browsers listed in the question for both options.

.menu {
  float: left;
  left: 50%;
  position: relative;
}

.menu > ul {
  float: left;
  right: 50%;
  position: relative;
}

.menu ul {
  margin: 0;
  padding: 0;
  list-style: none;
}

.menu ul:after {
  content: '';
  display: table;
  clear: both;
}

.menu > ul > li {
  text-align: left;
  float: left;
  position: relative;
}

.menu li ul {
  text-align: left;
  position: absolute;
  visibility: hidden;
  opacity: 0; 
}

.menu li ul li {
  position: relative;
}

.menu li:hover > ul {
  visibility: visible;
  opacity: 1;
}
<div class="menu">
  <ul>
  <li><a href="">Пункт 1-1</a>
    <ul>
      <li><a href="">Пункт 2-1</a></li>
    </ul>
  </li>
  </ul>
</div>
Scroll to Top