Css位置儿童div绝对祖父母

问题描述 投票:0回答:1

我试图将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

css
1个回答
0
投票

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

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

10px - height of all next siblging 

.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;
}
<div class="window">

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

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

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

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

.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;
}
<div class="window">

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

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

© www.soinside.com 2019 - 2024. All rights reserved.