If you want to center something horizontally in CSS you can do it just by, using the text-align: center; (when working with inline elements) or margin: 0 auto; (when working with block element). But when it comes to center something both horizontally and vertically the job can be a little tricky to achieve.
In this article, we’ll check out several techniques to completely center an element. You can find the complete code on codepen.io/jscodelover
Using Position and Transform property
.parent{
position: relative;
}
.child{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
These properties are set on the child element. Absolute positioning bases the element’s position relative to the nearest parent element that has position: relative
. If it can’t find one, it will be relative to the document. Add top: 50%; left: 50%;
because the position is calculated from the top left corner.
You must pull back the item with the half of its width and height. You can achieve this with transform: translate(-50%, -50%);