38
loading...
This website collects cookies to deliver better user experience
margin: auto
), but for simplicity and to give some background on how things have evolved, I'm going to center only on these five:Note: Do not use this method.
<table>
<tr>
<td>
Centered content
</td>
</tr>
</table>
table {
width: 100%;
height: 100%;
}
td {
vertical-align: center;
text-align: center;
}
Note: Avoid this method.
<div>Centered content</div>
div {
position: absolute;
top: 50%;
left: 50%;
width: 200px;
height: 60px;
line-height: 60px;
margin-left: -100px;
margin-top: -30px;
text-align: center;
}
line-height
could cause problems with multiline, etc.calc
function to avoid those issues," and they will be correct... now. But back then, CSS custom properties were not supported by that many browsers, and the support for calc
was slightly better.transform
:<div>Centered content</div>
div {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
position: absolute
, we are getting the element out of the normal flow of the page. Combined with the transform, this may cause the element to overlap other things on the page.<div>Centered content</div>
div {
display: flex;
align-items: center;
justify-content: center;
}
text-align: center
to center everything fully.display
from flex
to grid
, and it will all work the same:<div>Centered content</div>
div {
display: grid;
align-items: center;
justify-content: center;
}
align-items
and justify-content
into a single property: place-items
, making things slightly shorter:<div>Centered content</div>
div {
display: grid;
place-items: center;
}
transform: translate(-50%, -50%)
(#3) and FlexBox/Grid (#4 or #5) depending on the situation.position
set.) While in the FlexBox/Grid method, the styles go in the parent, and the element is oblivious to the positioning. It just is, which is beautiful and a more natural way of doing it.