How to center a div horizontally and vertically in CSS?

The easiest way is Flexbox on the parent.

.parent {
  display: flex;
  justify-content: center;   /* horizontal */
  align-items: center;       /* vertical */
  height: 200px;
}
Output in the browser
Centred

To centre only horizontally, give the box a width and use auto margins:

.box { width: 300px; margin: 0 auto; }

Grid also works: display: grid; place-items: center;.


Learn more about the similar topics:
Tutorials
CSS Flexbox
CSS Grid
Exercises & Assignments
Write CSS to centre a div horizontally and vertically using Flexbox
Write CSS to create a three column layout using Flexbox
Write CSS to create a responsive card grid using CSS Grid
Interview Questions & Answers
What is Flexbox in CSS?
What is the difference between Flexbox and Grid?
How to center a div horizontally and vertically in CSS?