Center Absolute Element: CSS Positioned Guide
When using position: absolute, you can center an element using the following methods:
- halfway up
- half of it is on the left side
- adjust: move halfway in both directions
Here is an example code:
.parent {
position: relative;
width: 300px;
height: 200px;
background-color: lightgray;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
In the above code, .parent represents the parent element, and .child represents the child element. The parent element sets the width and height with a gray background. The child element is positioned using position: absolute and is aligned to the center of the parent element by setting top: 50% and left: 50%. transform: translate(-50%, -50%) moves the child element to the top left corner by half of its own width and height, aligning the center of the child element with the center of the parent element.
With the above code, the child elements will be centered within the parent element.