绝对div内的绝对div相对于相对位置截断

时间:2019-09-26 12:29:28

标签: html css css-position

我彼此之间有3个div,并且具有以下CSS。

.d1 {
    position: relative;
    background-color: yellow;
    height: 50px;
    width: 100px;
    overflow: hidden;
}

.d2 {
    position: absolute;
    background-color: green;
    height: 25px;
    width: 50px;
}

.d3 {
    position: absolute;
    left: 83px;
}

和具有类的div如下:

<div class="d1">
  <div class="d2">
    <div class="d3">text</div>
  </div>
</div>

结果是我看到d3的内容由于溢出而被截断:隐藏在d1中。

enter image description here

如何避免不修改d1而切断d3的内容?

1 个答案:

答案 0 :(得分:0)

解决溢出问题。

通过将元素的relative设置为absolute,元素可以从位置为positionfixed的父元素溢出。具有position: fixed的元素将具有默认的leftrighttopbottom样式设置为auto。这会将.d3置于.d2的左上角,然后left: 83px样式会将其从此处推到左侧。

占用更多空间。

但是,要使该额外的移动作为原始标记移到右侧,您将需要添加margin-left: 8px,这将弥补复制原始文件所需的额外〜8px。需要通过设置.d3样式(请参见下文)对margin的位置进行进一步的调整。

您更新的代码应如下所示。

.d1 {
   position: relative;
   background-color: yellow;
   height: 50px;
   width: 100px;
   overflow: hidden;
}

.d2 {
  position: absolute;
  background-color: green;
  height: 25px;
  width: 50px;
}

.d3 {
 position: fixed;
 margin-left: 8px;
 left: 83px;
}

一些注意事项和警告。

如先前的评论者所述,最佳实践是修复html标记,因为如果您需要移动.d3的位置,则此解决方案可能会引起问题。例如,设置leftrighttopbottom将导致取消设置此样式的默认设置auto和元素将相对于视口而不是父relativeabsolute元素定位。