I have a parent element that is absolutely positioned, and three children.
When I make the first child to be positioned absolutely, the second child moves up and behind the first. This is expected.
When I make the first and second child to be positioned absolutely, the third child moves up and behind the first and second children. This is expected.
But when I make all the children to be positioned absolutely, the children move out of the parent completely. Why and how to rectify this?
Here’s the code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
html,
body {
height: 100%;
width: 100%;
}
.parent {
position: absolute;
top: 30px;
right: 30px;
border: 1px solid blue;
}
.child.line1 {
position: absolute;
height: 10px;
width: 10px;
background-color: red;
}
.child.line2 {
position: absolute;
height: 10px;
width: 10px;
background-color: lightblue;
}
.child.line3 {
position: absolute;
height: 10px;
width: 10px;
background-color: green;
}
</style>
</head>
<body>
<div style="height: 100%; display: flex; align-items: center; justify-content: center;">
<div style="position: fixed; height: 200px; width: 200px; background-color: bisque;">
<div class="parent">
<div class="child line1"></div>
<div class="child line2"></div>
<div class="child line3"></div>
</div>
</div>
</div>
</body>
</html>
2
Answers
No, children are inside parent element even when they all have position absolute.
Problem is with your parent element.
You didn’t set width and height of parent element, so when you set all children to absolute position, parent element’s with and height is 0.
Litlle blue square which is "outside" of the parent is just parent’s border.
If you add
width: 10px;
,height: 10px;
andbox-sizing: content-box;
to the .parent everything would look like you expected.Here is codepan: https://codepen.io/milanh212/pen/YzRbWQz
P.S. You should always set top/bottom and left/right to absolute/fixed positioned elements to be sure that they will be where you want them always in every browser and any device.
In your case, you should add:
First, you have to set the height and width of the parent to the size of the box, and the inner box should be dimensioned from the top, then it will come in line after line.
The code is written below, please check it. Hope it will work for you.