简体   繁体   English

如果元素在容器之外,是否可以相对于容器进行绝对定位?

[英]Is it possible to position an element with absolute positioning relative to a container if it is OUTSIDE the container?

Lets say you have two divs: 假设您有两个div:

<div class="div1"></div>
<div class="div2"></div>

div1 has relative positioning and div2 has absolute positioning. div1具有相对定位,而div2具有绝对定位。 Can div2 be positioned as if it was inside div1 either using CSS or pure Javascript? 可以使用CSS或纯Javascript将div2定位为好像位于div1内吗?

Using JavaScript. 使用JavaScript。

You have to wrap divs inside parent container with position: absolute and set div2 position to absolute as well. 您必须将divs包装在具有位置:absolute的父容器中,并将div2位置也设置为absolute。

<div class="wrap">
    <div class="div1"></div>
    <div class="div2"></div>
</div>

And then using javascript: 然后使用javascript:

var div1 = document.querySelector(".div1");
var div2 = document.querySelector(".div2");

div2.style.left = div1.offsetLeft + 'px';
div2.style.top = div1.offsetTop + 'px';

See JS fiddle 参见JS小提琴

Maybe this fits your question? 也许这符合您的问题? http://jsfiddle.net/bghxmm3o/ http://jsfiddle.net/bghxmm3o/

Absolute div2 (blue) positioned into relative div1 (red). 绝对div2(蓝色)位于相对div1(红色)中。

It's just CSS: 这只是CSS:

#d1 {
    position:relative;
    top:10px;
    left:10px;
    width:200px;
    height:200px;
    background:red;
}
#d2 {
    position:absolute;
    top:100px;
    left:50px;
    width:20px;
    height:20px;
    background:blue;
}

Yes and no, it depends on how you build it and the surrounding HTML. 是和否,这取决于您如何构建它以及周围的HTML。 If you put this code directly inside the body then yes, because the body would then be the parent element of both .div1 and .div2. 如果将这段代码直接放在主体内,则可以,因为主体将成为.div1和.div2的父元素。 And if you didn't know it already positioning something absolute positions the element to the top left corner of the "closest" relative positioned parent element. 而且,如果您不知道它已经定位了绝对位置,则将该元素定位在“相对”相对定位的父元素的左上角。 (Hard to explain in text) (很难用文字解释)

But if you were to have other HTML outside these two div elements, then you would need a parent element with a position relative. 但是,如果要在这两个div元素之外添加其他HTML,则需要一个具有相对位置的父元素。

So as an example: 因此,例如:

HTML HTML

<div class="parent">
    <div class="div1"></div>
    <div class="div2"></div>
</div>

CSS CSS

.parent {
    float:left;
    position:relative;
}

.box1 {
    width:100px;
    height:100px;
    float:left;
    position:relative;
}

.box2 {
    width:100px;
    height:100px;
    position:absolute;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM