Middle+
How to center a block horizontally and vertically?
sobes.tech AI
Answer from AI
There are several ways to center a block horizontally and vertically in CSS. One of the most versatile and modern methods is to use Flexbox.
Example:
.parent {
display: flex;
justify-content: center; /* horizontal centering */
align-items: center; /* vertical centering */
height: 100vh; /* so that the parent takes up the full height of the window */
}
.child {
/* block size */
width: 200px;
height: 100px;
background-color: lightblue;
}
HTML:
<div class="parent">
<div class="child">Centered block</div>
</div>
Other methods:
- Using CSS Grid with
place-items: center; - Absolute positioning with
top: 50%; left: 50%; transform: translate(-50%, -50%);
But Flexbox is simpler and most often preferred for such tasks.