This is one of the most frequently asked questions by newbie web designers; How to truly center an element with CSS? There are three ways that I know of to achieve this — using transforms, flexbox, or grid. My favorite is the flexbox method, but I’ll show you all three.
Using Flexbox
If you want to center a child element horizontally within its parent, you need to explicitly define the height of the parent element. justify-content
defines the alignment of child elements within a flexbox parent element on the x-axis. On the other hand, align-items
clarify how child elements within a flexbox element are aligned on the y-axis.
Using Grids
The grid method is very similar to the flexbox method. justify-content aligns grid items on the x-axis or row, while align-content aligns grid content on the y-axis or column.
This grid method is more useful when you want to center multiple elements in multiple rows and columns. The flexbox method is more suited for elements in single rows or columns.
Using Transform
The position of the child element is set absolute for the transform method. So we can manipulate its positioning. We top:50% and left 50% because absolute positioning in CSS calculates from the top left corner.
We then use the translate value of the transform property to move the element back half of its width and height, thereby positioning it in the center.
Blog Credits: Linda Ikechukwu
Comments are closed.