htmlcssflexboxpositioning

Does flexbox center absolute positioned div if no bottom/top/right/left attrs provided?


Why is my menu (position: absolute) affected by align-items: center?

Using top: 0 solves the problem, but I'd like to find out why this fixes the issue.

.navbar {
  padding-top: 50px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  /* WHY DOES THIS AFFECTS absolute positioned menu? */
}

.links {
  list-style: none;
  margin: 0;
  padding: 0;
  display: flex;
  gap: 40px;
}

.close {
  align-self: flex-end;
}

.burger,
.close {
  cursor: pointer;
  outline: none;
  border: none;
  background: none;
  padding: 0;
  user-select: none;
  display: inline-block;
}

.menu {
  display: block;
  position: absolute;
  width: 65vw;
  height: 300px;
  /* height: 100vh; */
  /* top: 0; IT SOLVES THE PROBLEM
  right: 0; */
  background-color: green;
  color: var(--dark-space-blue);
  z-index: 10;
}

.menu ul {
  list-style: none;
  display: flex;
  flex-direction: column;
  gap: 5px;
  margin: 0;
  padding: 0;
}
<nav class="navbar">
  <img src="assets/images/logo.svg" alt="">
  <button class="burger">
    <svg width="40" height="17" xmlns="http://www.w3.org/2000/svg"><g fill="#00001A" fill-rule="evenodd"><path d="M0 0h40v3H0zM0 7h40v3H0zM0 14h40v3H0z"/><path d="M0 0h40v3H0z"/></g></svg>
  </button>

  <div class="menu">
    <button class="close">
      <svg width="32" height="31" xmlns="http://www.w3.org/2000/svg"><g fill="#00001A" fill-rule="evenodd"><path d="m2.919.297 28.284 28.284-2.122 2.122L.797 2.419z"/><path d="M.797 28.581 29.081.297l2.122 2.122L2.919 30.703z"/></g></svg>
    </button>
    <ul>
      <li><a>Home</a></li>
      <li><a>New</a></li>
      <li><a>Popular</a></li>
      <li><a>Trending</a></li>
      <li><a>Categories</a></li>
    </ul>
  </div>
</nav>

codepen


Solution

  • From the specification

    The static position of an absolutely-positioned child of a flex container is determined such that the child is positioned as if it were the sole flex item in the flex container,

    Which results in

    The effect of this is that if you set, for example, align-self: center; on an absolutely-positioned child of a flex container, auto offsets on the child will center it in the flex container’s cross axis.

    So never rely on the static position when dealing with absolute element. Always set top/left/right/bottom to have full control over the position.