【问题标题】:absolute div inside absolute div cuts off with respect to relative position绝对 div 内的绝对 div 相对于相对位置截断
【发布时间】:2019-09-26 21:09:23
【问题描述】:

我有 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 中。

如何在不修改d1的情况下避免截断d3的内容?

【问题讨论】:

  • 这是不可能的。父元素上的overflow: hidden 将始终隐藏溢出的子元素。还有其他方法可以解决这个问题,但您必须重新构建 HTML 才能实现它。
  • 也许这会对你有所帮助:stackoverflow.com/questions/8837050/…
  • 确保 d3 在 d1 的范围内,不是吗?我的意思是设置它的宽度:left: 83px; width: 17px;

标签: html css css-position


【解决方案1】:

绕过溢出..

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

弥补额外的空间..

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

您更新后的代码应如下所示..

.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 元素。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多