In this example, we will see how to display an element at the center of a container using CSS. In CSS, we can align an element exactly at the center using flex. In this example, we will center an element vertically, horizontally, and both horizontally and vertically using flex. For this, we need to define display: flex
in the container element's CSS.
The flex uses justify-content
property to set the alignment of the items horizontally. The justify-content: center
horizontally displays an element exactly at the center of its container.
.container{
height: 400px;
width: 400px;
border: 2px solid black;
display: flex;
justify-content: center;
}
.element{
height: 50px;
width: 50px;
background-color: blue;
}
The flex uses align-items
property to set the alignment of the items vertically. The align-items: center
vertically aligns the element exactly at the center of its container.
.container{
height: 400px;
width: 400px;
border: 2px solid black;
display: flex;
align-items: center;
}
.element{
height: 50px;
width: 50px;
background-color: blue;
}
We can use align-items
property and justify-content
property to set the alignment of the items both horizontally and vertically. We need to set the value of both align-items
and justify-content
to center
.
.container{
height: 400px;
width: 400px;
border: 2px solid black;
display: flex;
align-items: center;
justify-content: center;
}
.element{
height: 50px;
width: 50px;
background-color: blue;
}
In this example, we displayed an element at the center of its container vertical, horizontally, and both vertically and horizontally using the justify-content and align-items property of with display: flex
value in CSS.