Vertically and horizontally centers a child element within its parent element, using display: table
.
display: table
to make the .center
element behave like a <table>
element.height
and width
to 100%
to make the element fill the available space within its parent element.display: table-cell
on the child element to make it behave like a <td>
elements.text-align: center
and vertical-align: middle
on the child element to center it horizontally and vertically..container
) must have a fixed width
and height
.<div class="container">
<div class="center"><span>Centered content</span></div>
</div>
.container {
border: 1px solid #9C27B0;
height: 250px;
width: 250px;
}
.center {
display: table;
height: 100%;
width: 100%;
}
.center > span {
display: table-cell;
text-align: center;
vertical-align: middle;
}
Snippet collection
A collection of techniques for centering HTML elements in any situation using CSS.
CSS, Layout
Horizontally and vertically centers a child element within a parent element using flexbox.
CSS, Layout
Horizontally and vertically centers a child element within a parent element using grid
.
CSS, Layout
Vertically and horizontally centers a child element within its parent element using CSS transforms.