m0meni
m0meni

Reputation: 16445

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 class="div1"></div>
<div class="div2"></div>

div1 has relative positioning and div2 has absolute positioning. Can div2 be positioned as if it was inside div1 either using CSS or pure Javascript?

Upvotes: 0

Views: 114

Answers (3)

Max Sandelin
Max Sandelin

Reputation: 140

Yes and no, it depends on how you build it and the surrounding 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. 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.

So as an example:

HTML

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

CSS

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

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

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

Upvotes: 0

Jiř&#237; H&#253;bek
Jiř&#237; H&#253;bek

Reputation: 381

Using JavaScript.

You have to wrap divs inside parent container with position: absolute and set div2 position to absolute as well.

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

And then using 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

Upvotes: 1

Jens A. Koch
Jens A. Koch

Reputation: 41776

Maybe this fits your question? http://jsfiddle.net/bghxmm3o/

Absolute div2 (blue) positioned into relative div1 (red).

It's just 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;
}

Upvotes: 0

Related Questions