div元素或文字水平垂直居中的5中方法
第一种方法:使用 top: 50%/left: 50%和translateX(-50%) translateY(-50%);具体代码如下:
.container {
position: absolute;
top: 50%;
left: 50%;
transform: translateX(-50%) translateY(-50%);
}
实例:
<!DOCTYPE html>
<html>
<head>
< charset=\"utf-8\">
< >如何让元素或文字水平垂直居中</ >
<style>
.container {
position: absolute;
top: 50%;
left: 50%;
transform: translateX(-50%) translateY(-50%);
}
</style>
</head>
<body class=\"container\">
文字水平垂直居中
</body>
</html>
方法二:使用display: flex; align-items: center; justify-content: center;属性
html, body, .container {
height: 100%;
}
.container {
display: flex;
align-items: center;
justify-content: center;
}
实例:
<!DOCTYPE html>
<html>
<head>
< charset=\"utf-8\">
< >如何让元素或文字水平垂直居中</ >
<style>
html, body, .container {
height: 100%;
}
.container {
display: flex;
align-items: center;
justify-content: center;
}
</style>
</head>
<body>
<div class=\"container\">
文字水平垂直居中
</div>
</body>
方法三:使用table-cell/vertical-align: middle
html, body {
height: 100%;
}
.parent {
width: 100%;
height: 100%;
display: table;
text-align: center;
}
.parent > .child {
display: table-cell;
vertical-align: middle;
}
实例:
<!DOCTYPE html>
<html>
<head>
< charset=\"utf-8\">
< >如何让元素或文字水平垂直居中</ >
<style>
html, body {
height: 100%;
}
.parent {
width: 100%;
height: 100%;
display: table;
text-align: center;
}
.parent .child {
display: table-cell;
vertical-align: middle;
} justify-content: center;
</style>
</head>
<body>
<div class=\"parent\">
<div class=\"child\">如何让元素或文字水平垂直居中</div>
</div>
</body>
</html>
方法四:line-height
.parent {
height: 200px;
width: 400px;
text-align: center;
}
.parent > .child {
line-height: 200px;
}
实例:
<!DOCTYPE html>
<html>
<head>
< charset=\"utf-8\">
< >如何让元素或文字水平垂直居中</ >
<style>
.parent {
height: 200px;
width: 400px;
text-align: center;
background:red;
}
.parent .child {
line-height: 200px;
}
</style>
</head>
<body>
<div class=\"parent\">
<div class=\"child\">如何让元素或文字水平垂直居中</div>
</div>
</body>
</html>
继续阅读与本文标签相同的文章
-
性能优化之卡顿延迟
2026-05-14栏目: 教程
-
第16问:Filecoin从DSN角度解读
2026-05-14栏目: 教程
-
C/C+从零基础到精通,究竟是如何快速完成的?其实只需要这6步!
2026-05-14栏目: 教程
-
谷歌再爆重大安全漏洞!华为却成最大赢家?网友:这谁还敢用!
2026-05-14栏目: 教程
-
Excel崩溃文件如何找回
2026-05-14栏目: 教程
