Reputation: 502
I'm aware of the position:relative
and position:absolute
trick to position a div relative to its parent. But what if the div is not its parent and I want to position it relative to that? I'm trying to implement something along those lines.
I'm also aware of position:fixed
to fix a div but I'm building a responsive website and I'd like to avoid that. I found a question here which mentions using jQuery to do it: How to position one element relative to another with jQuery? Is jQuery the only way to do it? Can it be done using CSS as well?
I've put up a fiddle here: http://jsfiddle.net/19bdpgsf/. In the fiddle, I'm trying to position the child2
element relative to the notparentdiv
just like it has been positioned relative to the parent
div. Is it possible using only css?
Thanks.
Upvotes: 21
Views: 21312
Reputation: 276
var position = document.getElementById("relative");
document.getElementById("").appendChild(position);
maybe use something like this to move the div into the div you want it in?
This will place a div into the desired div, and from there position:relative;
will work.
Upvotes: 1
Reputation: 1053
Another way if you dont want to use css positions use offset jquery as below to position you div
var nonparent = $('.notParent');
var position = nonparent.offset();
$('.child1').offset({
top: position.top,
left: position.left
});
.notParent {
background-color: red;
padding: 20px;
}
.child2 {
background-color: yellow;
}
.child1 {
background-color: green;
}
.parent {
background-color: purple;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="notParent">
not parent div
</div>
<br/>
<br/>
<br/>
<br/>
<div class="parent">
parent
<div class="child1">child1</div>
<div class="child2">
child2
</div>
</div>
You can position a div inside another div which is not parent with absolute relative positions as below
.notParent {
background-color: red;
position: relative;
}
.child2 {
background-color: yellow;
position: absolute;
top: 10px;
}
.child1 {
background-color: green;
top: 30px;
}
.parent {
background-color: purple;
}
<div class="notParent">
not parent div
</div>
<br/>
<br/>
<br/>
<br/>
<div class="parent">
parent
<div class="child1">child1</div>
<div class="child2">
child2
</div>
</div>
Upvotes: 4
Reputation: 2582
You could use absolute positioning (relative to the entire body of the page), but other than that I don't think there's any other way than jQuery.
Upvotes: 0