What are the different ways to center an element horizontally and vertically using CSS?

1 Answers
Answered by suresh

Ways to center an element horizontally and vertically in CSS

There are several ways to center an element both horizontally and vertically using CSS:

  1. Using Flexbox: Set the parent container's display property to flex and use justify-content: center; and align-items: center; on the parent container.
  2. Using Grid: Set the parent container's display property to grid and use place-items: center; on the parent container.
  3. Absolute Positioning: Set the element to be centered using position: absolute;, and then use top: 50%;, left: 50%;, transform: translate(-50%, -50%); to center it.
  4. CSS Table Display: Set the parent container's display property to table; and use display: table-cell; and vertical-align: middle; on the child element.
  5. Using CSS Grid with Auto Margins: Set the parent container's display property to grid and use margin: auto; on the centered element.
Answer for Question: What are the different ways to center an element horizontally and vertically using CSS?