Interview question: css2(old browser compatible like IE) align horizontal center and align vertical center

Witch Elaina
1 min readOct 12, 2021

css2-align-center.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<!--mobile friendly-->
<meta name="viewport" content="width=device-width, user-scalable=yes">
<style>
/**
if I can use css3, don't use following, use flex align instead(more easy)
*/
.c {
width: 200px;
height: 200px;
background-color: pink;
margin: 20px;
}
.center1 {
text-align: center;
}
.center2 {
display: table;
}
.center2 > * {
/* use display: table-cell is better display:inline-block, when use inline-block vertical align is very hard see https://www.jianshu.com/p/dea069fecb62 */
display: table-cell;
vertical-align: middle;
}
</style>
</head>
<body>
<!-- the best align center way is flex, in real case, use flex don't use other way, other ways maybe have hidden make-it-work condition-->
<div class="c center1">
text-align: center;
</div>
<div class="c center2">
<div> .center2 {
display: table;
}
.center2 > * {
display: table-cell;
vertical-align: middle;
}
</div>
</div>
</body>
</html>

If you like my article, donate me a coffee and let me continue

Donate

Donate backup

--

--