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.
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.
<div class="centered_element"></div>
.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.
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.
<div class=“containerâ€>
<div class=“boxâ€></div>
</div>
.container {
display: flex;
justify-content: center;
align-items: center;
}
.box {
height: 200px;
width: 200px;
background: #ddd;
}
You can use transform CSS property to center element vertically and horizontally.
<div class=“elemâ€></div>
.elem {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
You can also use display: table-cell; property and verically align items inside it as an old approach