html code

3 Ways To Center A Div In CSS

Sometimes we forget how to center a div in CSS, but you don't need to care about it. I'm going to show you three ways to do that.

Method 1: Margin Auto

In this method, the div needs to have a width setted to work. The margin: auto
property will automatically center the div within its parent container. However, keep in mind that this method only works for horizontally centering.

Method 1: Margin Auto

Here's an example:

.center-div {
width: 200px;
margin: auto;
}

Method 2: Flexbox

In this way, by setting the display property to flex and the justify-content and align-items properties to center on the parent element, the child elements will align both horizontally and vertically within the container.

Method 2: Flexbox

.parent-div {
display: flex;
justify-content: center;
align-items: center;
}

Method 3: Grid

In this method, by setting the display property to grid and using the place-items property to center on the parent container, the child elements will align both horizontally and vertically within the parent container.

Method 3: Grid

.parent-div {
display: grid;
place-items: center;
}