ScanSkill
CSS Examples

How to Display an Element at the Center of a Container Using CSS

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.

Prerequisites

Example

Center an Element Horizontally Using Flex

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;
        }
How to Display an Element at the Center of a Container Using CSS

Center an Element Vertically Using Flex

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;
        }
How to Display an Element at the Center of a Container Using CSS

Center an Element Both Horizontally and Vertically Using Flex

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;
        }
How to Display an Element at the Center of a Container Using CSS

Conclusion

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.