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 |
| 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? |