Reputation: 136
I want to position a div
element under another div element with an absolute position. This is what I have so far:
.div1 {
position: absolute;
top: 0;
bottom: 0;
width: 25%;
}
.div2 {
position: absolute;
top: 0;
left: 25%;
bottom: 0;
width: 75%;
background-color: Coral;
}
.div3 {
position: absolute;
top: 50%;
left: 25%;
bottom: 0;
width: 75%;
background-color: Aquamarine;
}
<div class="div1"></div>
<div class="div2"></div>
<div class="div3"></div>
(Run code snippet to see what I have)
And I want .div3
(The blue box) to be below .div1
(White) and .div2
(Orange) so you need to scroll the page to see .div3
. Right now, blue is overlapping orange. Can anyone help me out?
Upvotes: 0
Views: 1405
Reputation: 206
I believe this does what you're asking for:
.div1 {
position: absolute;
top: 0;
bottom: 0;
width: 25%;
}
.div2 {
position: absolute;
top: 0;
left: 25%;
bottom: 0;
width: 75%;
background-color: Coral;
}
.div3 {
position: absolute;
top: 100%;
left: 0;
bottom: 0;
width: 100%;
height: 100%;
background-color: Aquamarine;
}
<div class="div1"></div>
<div class="div2"></div>
<div class="div3"></div>
I think the misconception came from writing the lengths as percentages aka width: 100%
. In css the %
unit means relative to the closest positioned ancestor which in your case is the html itself or the view window. So 100% represents the entire width or height of the window you can see. Setting the top
property of div3
to 100% ensures that it will drawn with the top edge along the bottom of the screen.
Upvotes: 1
Reputation: 805
They should have the same parent with the position relative
(in this case I used body
). And then you should use z-index
to specify the stack order of the element. An element with greater stack order is always in front of an element with a lower stack order. .div2
and .div3
should not have the same bottom
value. otherwise you can never see the blue one. cause they both stretch to the bottom of the page.
body {
padding: 0;
margin: 0;
min-height: 200vh;
position: relative;
}
.div1 {
position: absolute;
top: 0;
bottom: 0;
width: 25%;
z-index: 2;
background: rgba(255, 0, 0, 1);
}
.div2 {
position: absolute;
top: 0;
left: 25%;
bottom: 50%;
width: 75%;
background-color: rgba(0, 255, 0, 1);;
z-index: 2;
}
.div3 {
position: absolute;
top: 50%;
left: 25%;
bottom: 0;
width: 75%;
background-color: rgba(0, 0, 255, 1);;
z-index: 1;
}
<div class="div1"></div>
<div class="div2"></div>
<div class="div3"></div>
Upvotes: 1