CSS(层叠样式表)是一种用于描述HTML或XML(包括SVG、MathML等各种XML方言)文档样式的样式表语言。在CSS中,有多种方法可以实现文本在div中的居中对齐。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>水平居中示例</title>
<style>
.container {
text-align: center;
}
</style>
</head>
<body>
<div class="container">
<p>这段文本在水平方向上居中</p>
</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>垂直居中示例</title>
<style>
.container {
display: flex;
align-items: center;
height: 200px;
}
</style>
</head>
<body>
<div class="container">
<p>这段文本在垂直方向上居中</p>
</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>水平和垂直居中示例</title>
<style>
.container {
display: flex;
justify-content: center;
align-items: center;
height: 200px;
}
</style>
</head>
<body>
<div class="container">
<p>这段文本在水平和垂直方向上都居中</p>
</div>
</body>
</html>
原因:
解决方法:
通过以上方法,你可以轻松实现CSS字体在div中的居中对齐。
领取专属 10元无门槛券
手把手带您无忧上云