当 parent 具有相对定位时,悬停菜单的 max-width 被忽略

Hover menu's max-width being ignored when parent has a relative positioning

当parent是相对

时,绝对定位元素的宽度受限

我有一个导航栏,悬停时有一个菜单。菜单将包含标签,标签中文本的长度会有所不同。

我希望菜单具有最小和最大宽度 child div 必须设置为 min-width/max-width。但是无论菜单的宽度如何,都被限制在min-width点。

是否可以让 child div 忽略 parent 的宽度,同时仍然保持 child(我无法将其移出parent,我知道这是一个简单的解决方案)?

这是我遇到的行为示例:https://codepen.io/vee1234/pen/omQxWP

.navBar {
  background-color: #222;
  width: 50px;
  min-height: 100%;
  height: 100vh;
}

.navItem {
  color: #a1a1a1;
  padding-top: 15px;
  padding-bottom: 15px;
  position: relative;
}

.menu {
font-family: "Open Sans", sans-serif;
  position: absolute;
  display: none;
  min-width: 200px;
  max-width: 600px;
  background-color: #333;
  z-index: 100;
  left: 100%;
  top: 20%;
}

.menu div a {
  display:block;
  border: 1px solid red;
}

.navItem:hover .menu {
  display: block;
}
 <div class="navBar">
    <div class="navItem">
      <div>Nav Menu Trigger</div>
      <div class="menu">
        <div class="link">
          <a>string of any length</a>
          <a>string of any length - but this one is super long</a>
        </div>
      </div>
    </div>
    <div class="navItem">
      <div>Nav Menu Trigger</div>
      <div class="menu">
        <div class="link">
          <a>string of any length</a>
          <a>string of any length - but this one is super long</a>
        </div>
      </div>
    </div>
     <div class="navItem">
      <div>Nav Menu Trigger</div>
      <div className="menu">
        <div className="link">
          <a>string of any length</a>
          <a>string of any length - but this one is super long</a>
        </div>
      </div>
    </div>
  </div>

绝对定位将元素从它在 DOM 中的实际位置移出,并将其定位在您指定的位置。因此,该元素失去了对有助于确定宽度的父元素的引用。您需要明确设置宽度。

一个技巧是通过添加一些 padding-right 来使相对元素更大,这不会影响文本在内部的方式,但会被计算在绝对元素的宽度计算中。然后只给你想要的部分上色。您还可以添加负边距以纠正添加的填充。

.menu {
  width:50px;
  padding-right:500px;
  margin-right:-500px;
  background:#000 content-box;
  height:100px;
  position:relative;
  color:#fff;
}

.menu div{
  position:absolute;
  top:0;
  left:50px;
  background:blue;
  min-width:200px;
  max-width:500px;
}
.menu div a {
  border:1px solid;
  display:block;
}
<div class="menu">
 some text here
  <div>
    <a>some text here</a>
    <a>some text here some text here some text here some text here some text here some text here some text here some text here</a>
    <a>some text here</a>
  </div>
</div>