Six ways to center content horizontally and vertically
There are several ways to achieve horizontal and vertical centering of a div; here are six of them.
- Use flexbox layout: set the parent element to display: flex; and use justify-content: center; and align-items: center; to horizontally and vertically center the child elements.
- Utilize absolute positioning: set the parent element to relative positioning (position: relative;), and the child element to absolute positioning (position: absolute;), then set top: 50% and left: 50% to move the top left corner of the child element to the center of the parent element, and finally use transform: translate(-50%, -50%); to align the center of the child element to the center of the parent element.
- Use table layout: set the parent element to display: table; and the child element to display: table-cell;, then use vertical-align: middle; to vertically center the child element, and use text-align: center; to horizontally center the child element.
- Use grid layout: set the parent element to display: grid; and use justify-items: center; and align-items: center; to center the child elements both horizontally and vertically.
- Using the transform property: set the parent element to relative positioning (position: relative;) and the child element to absolute positioning (position: absolute;), then use top: 50%; and left: 50%; to move the top-left corner of the child element to the center of the parent element, finally, use transform: translate(-50%, -50%); to align the center of the child element to the center of the parent element.
- Using the text-align and line-height properties: set the parent element’s text-align property to center, and then set the parent element’s line-height property to a value equal to the parent element’s height. This will automatically vertically align the child element. Use the text-align property to horizontally center-align the child element.
The above are six common methods for horizontally and vertically centering a div, the specific choice of method depends on the specific needs and layout.