Css位置儿童div绝对祖父母

时间:2018-03-01 15:25:31

标签: css

我正在尝试将div放在窗口的右下角,而不是右下角的父div。

例如

<div class="window">

 <div class="parent">
   <div class="child"></div>
 </div>

</div>

.window.parent都有position:relative;

.child有样式:

position:absolute;
bottom: 10;
right: 10;

但是这会将其定位到.parent而不是.window

1 个答案:

答案 0 :(得分:0)

没有通用方法,我们需要考虑不同的情况。如果我们认为父级没有指定高度/宽度,这意味着父级将具有与窗口相同的宽度,因此右侧属性是好的。对于高度,如果父级是窗口的最后一个子级,或者没有其他内容,则底部属性也很好。

现在如果父元素后面有元素,则底值应该等于

10px - height of all next siblging 

&#13;
&#13;
.window,
.parent {
  position: relative;
  border: 1px solid;
  min-height:50px;
}

.box {
  height: 100px;
  background:yellow;
}

.child {
  position: absolute;
  bottom: calc(10px - 200px);
  right: 10px;
  width: 20px;
  height: 20px;
  background:red;
}
&#13;
<div class="window">

  <div class="parent">
    <div class="child"></div>
  </div>
  <div class="box"></div>
  <div class="box"></div>
</div>
&#13;
&#13;
&#13;

如果为父元素指定了高度,则会应用相同的逻辑,因为我们正在考虑底部,因此父级的高度没有效果。

如果为父元素指定了宽度,则右侧属性应为

10px - (widow-width - parent-width)

&#13;
&#13;
.window,
.parent {
  position: relative;
  border: 1px solid;
  min-height:50px;
}
.window {
  width:500px;
}
.parent {
  width:200px;
}
.box {
  height: 100px;
  background:yellow;
}

.child {
  position: absolute;
  bottom: calc(10px - 200px);
  right: calc(10px - (500px - 200px)) ;
  width: 20px;
  height: 20px;
  background:red;
}
&#13;
<div class="window">

  <div class="parent">
    <div class="child"></div>
  </div>
  <div class="box"></div>
  <div class="box"></div>
</div>
&#13;
&#13;
&#13;

因此,您需要考虑自己的情况并根据需要调整值。当然,如果您的标记更复杂并且您应用了更多CSS,则情况并非如此。