There are several ways to center an element both horizontally and vertically on a web page, but the most
common approach is to use CSS. There are a few methods using CSS:
- Using flexbox
- Using grid
- Using position and transform
- Using flexbox:
Flexbox is a layout model that makes it relatively easy to center elements
both horizontally and vertically. We can apply it to the container element that surrounds the element we
want to center.
Example:
<html>
<head>
<style>
.container {
display: flex;
justify-content: center;
align-items: center;
height: 20vh;
}
.centered-element {
background-color: #308D46;
padding: 20px;
color: #fff;
}
</style>
</head>
<body>
<div class="container">
<div class="centered-element">Center me!</div>
</div>
</body>
</html>
Output:
- Using grid:
Set the display property of the first element to “grid” and use the
“place-items“ property to center the second element.
Example:
<!DOCTYPE html>
<html>
<head>
<style>
.container {
display: grid;
height: 20vh;
place-items: center;
}
.element {
background-color: #308D46;
padding: 20px;
color: #fff;
}
</style>
</head>
<body>
<div class="container">
<div class="element">CodeBetter</div>
</div>
</body>
</html>
Output:
- Using position and transform:
We can also center an element using absolute positioning. This
method is especially useful if we need to center an element within a specific container.
Example:
<html>
<head>
<style>
.container {
position: relative;
width: 100%;
height: 20vh;
}
.centered-element {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
</style>
</head>
<body>
<div class="container">
<div class="centered-element">Center me!</div>
</div>
</body>
</html>
Output: