| |
在 CSS 中,可以通过多种方式实现 div
内文本的水平和垂直居中。以下是几种常见的方法:
Flexbox 是现代布局中最常用的方法之一,它可以让子元素在父容器中水平和垂直居中。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Center Text</title>
<style>
.container {
display: flex;
justify-content: center; /* 水平居中 */
align-items: center; /* 垂直居中 */
height: 200px; /* 设置父容器的高度 */
border: 1px solid #000; /* 可选:添加边框以便观察 */
}
</style>
</head>
<body>
<div class="container">
<div>居中的文本</div>
</div>
</body>
</html>
CSS Grid 也可以实现水平和垂直居中,适用于更复杂的布局需求。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Center Text</title>
<style>
.container {
display: grid;
place-items: center; /* 水平和垂直居中 */
height: 200px; /* 设置父容器的高度 */
border: 1px solid #000; /* 可选:添加边框以便观察 */
}
</style>
</head>
<body>
<div class="container">
<div>居中的文本</div>
</div>
</body>
</html>
这种方法适用于需要兼容较旧浏览器的场景。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Center Text</title>
<style>
.container {
position: relative;
height: 200px; /* 设置父容器的高度 */
border: 1px solid #000; /* 可选:添加边框以便观察 */
}
.container div {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%); /* 水平和垂直居中 */
}
</style>
</head>
<body>
<div class="container">
<div>居中的文本</div>
</div>
</body>
</html>
line-height
和 text-align
这种方法适用于单行文本的居中,通过设置 line-height
和 text-align
来实现。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Center Text</title>
<style>
.container {
text-align: center; /* 水平居中 */
line-height: 200px; /* 垂直居中,设置为父容器的高度 */
height: 200px; /* 设置父容器的高度 */
border: 1px solid #000; /* 可选:添加边框以便观察 */
}
</style>
</head>
<body>
<div class="container">
居中的文本
</div>
</body>
</html>
display: table
和 display: table-cell
这种方法适用于需要兼容较旧浏览器的场景。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Center Text</title>
<style>
.container {
display: table;
width: 100%; /* 或者设置为固定宽度 */
height: 200px; /* 设置父容器的高度 */
border: 1px solid #000; /* 可选:添加边框以便观察 */
}
.container div {
display: table-cell;
text-align: center; /* 水平居中 */
vertical-align: middle; /* 垂直居中 */
}
</style>
</head>
<body>
<div class="container">
<div>居中的文本</div>
</div>
</body>
</html>
line-height
和 text-align
:适用于单行文本的居中。display: table
和 display: table-cell
:适用于需要兼容较旧浏览器的场景。根据你的具体需求和浏览器兼容性要求,选择合适的方法来实现 div
内文本的水平和垂直居中。
系列Course并未All上架,处于先行测试阶段