Center elements using CSS

There are several ways to center HTML elements vertically and horizontally using CSS. We are listing down some of them with explanation and usable code.

Center positioned elements

If you have applied position: absolute or position: fixed property on any element then you can center the element by providing height and width property to it along with CSS properties shown in the code.

HTML Code

<div class="centered_element"></div>

CSS Code

.centered_element {
   position: absolute; /*OR fixed*/
   width: 300px;
   height: 150px;
   background: #ccc;
   left: 0;
   right: 0;
   top: 0;
   bottom: 0;
   margin: auto;
}

We have used margin: auto to make the element centred with class name centered_element. When left: 0 and right: 0 properties are applied it will center it horizontally and if we apply top: 0 and bottom: 0 CSS properties, it will center the element vertically.

Use of Flexbox to center element 

You can use display: flex property on parent element to center its child element. To center the child horizontally use justify-content: center on parent and to align the child element vertically use property align-items: center on parent element. In the example code we have assigned class name ‘.container’ to the parent element and ‘.box’ class name to child element.

HTML Code

<div class=“container”>
    <div class=“box”></div>
</div>

CSS Code

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


.box {
    height: 200px;
    width: 200px;
    background: #ddd;
}

Using Transform

You can use transform CSS property to center element vertically and horizontally.

HTML Code

<div class=“elem”></div>

CSS Code

.elem {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
1 Comments

You can also use display: table-cell; property and verically align items inside it as an old approach

.container {
    display: table-cell;
    vertical-align: center;
}
Write new article
Never leave your website again in search of code snippets by installing our chrome extension.