There are several ways to center a div horizontally and vertically with CSS:
- Using :
.container {
display: flex;
justify-content: center;
align-items: center;
}
In this example, the
property of the container is set to
, which allows us to use the
and
properties to center the child elements both horizontally and vertically.
- Using :
.container {
display: grid;
place-items: center;
}
In this example, the
property of the container is set to
, and the
property is used to center the child elements both horizontally and vertically.
- Using and :
.container {
position: relative;
}
.centered-div {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
In this example, we've used a parent container with
to position the child div with
. We've set the
and
properties of the child div to
, and then used
transform: translate(-50%, -50%)
to center it.
Keep in mind that the third method requires the div to have a fixed width and height. If your div's dimensions are dynamic, you might need to use a different approach.