Middle+
What methods do you know for centering an element vertically?
sobes.tech AI
Answer from AI
There are several common ways to vertically center an element in CSS:
- Flexbox
.parent {
display: flex;
align-items: center; /* centers vertically */
justify-content: center; /* for horizontal centering */
}
- Grid
.parent {
display: grid;
place-items: center; /* centers vertically and horizontally */
}
- Positioning with transformation
.child {
position: absolute;
top: 50%;
transform: translateY(-50%);
}
- Table-cell alignment
.parent {
display: table-cell;
vertical-align: middle;
}
- Line-height (for single-line text)
.element {
height: 100px;
line-height: 100px; /* matches the container height */
}
The choice of method depends on the context and requirements for responsiveness and markup structure.