How can center-align an element both horizontally and vertically using CSS?
How can center-align an element both horizontally and vertically using CSS?
25407-Jun-2023
Updated on 09-Jun-2023
Aryan Kumar
09-Jun-2023There are a few ways to center-align an element both horizontally and vertically using CSS. Here are a few methods:
Using margin: 0 auto
One way to center-align an element both horizontally and vertically is to use the margin: 0 auto property. This property sets the margins on the left and right sides of the element to 0, and then automatically centers the element within its container.
For example, the following code would center-align the div element both horizontally and vertically:
Code snippet
Using text-align: center and vertical-align: middle
Another way to center-align an element both horizontally and vertically is to use the text-align: center and vertical-align: middle properties. The text-align: center property centers the text within the element, and the vertical-align: middle property centers the element vertically within its container.
For example, the following code would center-align the div element both horizontally and vertically:
Code snippet
Using display: table and text-align: center
If the element you want to center is a block element, you can use the display: table property to make it behave like a table. This will allow you to use the text-align: center property to center the element both horizontally and vertically.
For example, the following code would center-align the div element both horizontally and vertically:
Code snippet
Using display: flex and align-items: center
If you want to center-align multiple elements, you can use the display: flex property to make the container a flex container. This will allow you to use the align-items: center property to center the elements vertically within the container.
For example, the following code would center-align the div elements both horizontally and vertically:
Code snippet
Using display: grid and place-items: center
If you want to center-align multiple elements and have them take up equal space, you can use the display: grid property to make the container a grid container. This will allow you to use the place-items: center property to center the elements both horizontally and vertically within the container.
For example, the following code would center-align the div elements both horizontally and vertically and have them take up equal space:
Code snippet
Which method you use to center-align an element both horizontally and vertically will depend on your specific needs.