阻止绝对定位的子元素占用父元素的宽度

3
我有一个div(父元素),当鼠标悬停在上面时,会出现一个菜单。
父元素是30px X 30px。
菜单是一个绝对定位的元素,根据内容可以扩展到200px。
问题在于,子元素不会超过父元素的30px而扩展。但是我想让它扩展到其内容并在200px后停止扩展。
是否有其他方法可以做到这一点,而不必将子元素的宽度设为固定值?

.parent {
  width: 30px;
  height: 30px;
  line-height: 30px;
  text-align: center;
  background-color: yellow;
  border: 1px solid;
  position: relative;
}

.child {
  position: absolute;
  background-color: aqua;
  border: 1px solid;
  display: none;
  max-width: 200px;
}

.parent:hover .child {
  display: block;
}
<div class="parent">
  P
  <div class="child">
    Hey diddle diddle the cat and the fiddle.
  </div>
</div>

将鼠标悬停在父元素上,您可以看到子元素正在使用父元素的大小。


使用min-width而不是max-width? - Temani Afif
你想要类似于这个的东西吗? - raina77ow
@TemaniAfif 子元素上的文本是动态的。有时可能只有两个单词,而其他时候可能是整个句子。因此,我不能给它一个最小宽度,因为对于只有两三个单词的情况,它会太大了。很难在小文本和长文本之间平衡最小宽度。 - user3607282
@raina77ow 不行。当鼠标悬停时,父元素应该保持30像素。 - user3607282
2个回答

2

如果您不希望子元素的宽度受到其父元素的影响,则需要移除父元素的position: relative。看下面这个例子:

.parent {
  display: inline-block;
  width: 30px;
  height: 30px;
  line-height: 30px;
  text-align: center;
  background-color: yellow;
  border: 1px solid;
}

.child {
  position: absolute;
  background-color: aqua;
  border: 1px solid;
  display: none;
  max-width: 200px;
}

.parent:hover .child {
  display: block;
}
<div class="parent">
  P
  <div class="child">
    Hey diddle diddle the cat and the fiddle.
  </div>
</div>


0

如果我理解正确,您需要将菜单定位到最大200,并在可能的情况下填充菜单。问题是,父级元素只有30像素的宽度,菜单项是其子元素,因此如果不使用最小宽度,菜单项也只有30个像素。

子元素需要一个更宽的父元素。 尝试进行以下修改:

<script>
.title {
  width: 30px;
  height: 30px;
  line-height: 30px;
  text-align: center;
  background-color: yellow;
  border: 1px solid;
  position: relative;
}
.parent{
  position: relative;
}
.child {
  position: absolute;
  background-color: aqua;
  border: 1px solid;
  display: none;
  max-width: 200px;
}

.title:hover + .child {
  display: block;
}
</script>

<div class="parent">
<div class="title">P</div>
  <div class="child">
    Hey diddle diddle the cat and the fiddle.Hey diddle diddle the cat and the fiddle.Hey diddle diddle the cat and the fiddle.Hey diddle diddle the cat and the fiddle.
  </div>
</div>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接