CSS 文字居中是一种常见的布局技巧,可以通过多种方式实现。以下是几种常见的方法及其代码示例:
text-align
属性<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Text Align Center</title>
<style>
.center-text {
text-align: center;
}
</style>
</head>
<body>
<div class="center-text">
这段文字水平居中
</div>
</body>
</html>
margin
属性<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Margin Center</title>
<style>
.center-text {
display: inline-block;
margin-left: auto;
margin-right: auto;
}
</style>
</head>
<body>
<div class="center-text">
这段文字水平居中
</div>
</body>
</html>
line-height
属性<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Line Height Center</title>
<style>
.center-text {
height: 100px;
line-height: 100px;
text-align: center;
}
</style>
</head>
<body>
<div class="center-text">
这段文字垂直居中
</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>Flexbox Center</title>
<style>
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
</style>
</head>
<body>
<div class="container">
<div class="center-text">
这段文字垂直和水平居中
</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>Full Center</title>
<style>
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
</style>
</head>
<body>
<div class="container">
<div class="center-text">
这段文字完全居中
</div>
</div>
</body>
</html>
text-align: center;
不起作用?display
属性设置为 inline
。display
属性不是 inline
。display: flex;
。display: flex;
。通过以上方法,你可以轻松实现 CSS 文字居中,并解决常见的居中问题。
领取专属 10元无门槛券
手把手带您无忧上云