阻止位置绝对的孩子占用父母的宽度

时间:2018-08-30 09:48:44

标签: html css

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

父级为30像素X 30像素。

菜单是绝对位置元素,可以根据内容扩展到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>

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

2 个答案:

答案 0 :(得分: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>

答案 1 :(得分:0)

如果我的理解正确,那么您需要将菜单设置为最大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>
相关问题