当父级具有相对定位时,忽略悬停菜单的最大宽度

问题描述 投票:0回答:2

当父亲是相对的时,绝对定位元素的宽度受到约束

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

我希望菜单具有最小和最大宽度子div必须将min-width / max-width设置为。但无论菜单的宽度是多少都限制在最小宽度点。

是否有可能让子div忽略父级的宽度,同时仍然保持它的子级(我不能将它移出父级,我知道这将是一个简单的解决方案)?

这是我遇到的行为的一个例子: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>
css css3 css-position
2个回答
2
投票

一个技巧是通过添加一些不会影响文本内部的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>

0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.