markdown 如何更改绝对定位的CSS元素的偏移父元素?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown 如何更改绝对定位的CSS元素的偏移父元素?相关的知识,希望对你有一定的参考价值。

# [How can I change the offset parent of an absolutely positioned CSS element?](https://stackoverflow.com/questions/30945185/how-can-i-change-the-offset-parent-of-an-absolutely-positioned-css-element)

By default, an HTML element whose position is set to "absolute" will be positioned relative to the browser's viewport.

But if one of the element's ancestors is set to a non-static position, the element will be positioned relative to that ancestor. That ancestor is the element's "offset parent".

The problem: I want to absolute-position an element relative to the viewport, but unfortunately one of its ancestors is relatively positioned, so that has become its offset parent. Since I'm modifying a 3rd-party theme, I can't move the element or remove its ancestor's relative positioning.

Using CSS or JavaScript, is it possible for me to, in effect, set or reset an element's offset parent? I understand that the DOM property [element].offsetParent is read-only, but is there some way to indirectly have the effect of setting it?

----------

[You could use Javascript to move the element.](https://stackoverflow.com/a/30946697/6412747) Here is the jQuery solution with prependTo() function, you could also use appendTo().

[http://jsfiddle.net/6557cnew/](http://jsfiddle.net/6557cnew/)

```js
$(function() {
    $('.absolute').prependTo('body');
});
```
```css
.relative {
    position: relative;
    left: 50px;
    top: 50px;
    border: 1px solid blue;
    width: 100px;
    height: 100px;
}
.absolute {
    position: absolute;
    border: 1px solid red;
    left: 0;
    top: 0;
}
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div class="relative">
    relative
    <div class="absolute">
        absolute
    </div>
</div>
```

以上是关于markdown 如何更改绝对定位的CSS元素的偏移父元素?的主要内容,如果未能解决你的问题,请参考以下文章

我可以使用 CSS 过渡为绝对定位元素设置动画吗?

css绝对定位如何水平居中?

Flash 播放器覆盖绝对定位元素

如何在css中的绝对定位元素之间强制分页

CSS样式当时 CSS定位 绝对定位

markdown 快速找到绝对元素的相对定位的祖先