【问题标题】:Stop position absolute child from taking parent's width停止位置绝对子项占用父项的宽度
【发布时间】:2018-08-30 19:44:19
【问题描述】:

我有一个 div(父级),当它悬停时,会出现一个菜单。

父级为 30px X 30px。

菜单是一个绝对位置元素,可以根据内容扩展至200px。

这样做的问题是,子级不会超出父级的 30 像素。但我想要的是让它扩展到它的内容并在 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>

将鼠标悬停在父元素上以查看子元素正在采用父元素的大小。

【问题讨论】:

  • 最小宽度而不是最大宽度?
  • 你想要类似于this的smth吗?
  • @TemaniAfif 孩子身上的文字是动态的。有时它可以像 2 个单词。其他时候它可以是一个完整的句子。所以我不能给它 min-width 因为对于只有两个或三个单词的情况,它太大了。很难在小文本和长文本之间平衡最小宽度。
  • @raina77ow 不。将鼠标悬停在上时,父级应保持 30 像素。

标签: html css


【解决方案1】:

如果您不希望孩子的宽度受到其父母的影响,那么您必须删除父母的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>

【讨论】:

    【解决方案2】:

    如果我理解正确,您需要将菜单设置为最多 200 个,并尽可能填写。问题是,父级有 30px 宽度,而子级在其中,所以如果你不使用 min-with,它将有 30px。

    子元素需要一个宽度更大的父元素。 试试这个修改:

    <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>
    

    【讨论】:

      猜你喜欢
      • 2020-02-03
      • 2018-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-09
      • 1970-01-01
      • 1970-01-01
      • 2019-10-26
      相关资源
      最近更新 更多