
我们可以轻松地将文本在 div 内水平和垂直居中。让我们一一看看。
要将 div 中的文本水平居中,请使用 text-align 属性。 text-align 属性确定行框在块级元素内的对齐方式。以下是可能的值 -
left - 每个行框的左边缘与块级元素内容区域的左边缘对齐。
right - 每个行框的右边缘与块级元素内容区域的右边缘对齐。
center - 每个行框的中心与块级元素内容区域的中心对齐。
justify - 每个行框的边缘应与块级元素内容区域的边缘对齐。
字符串 - 列中单元格的内容将在给定字符串上对齐。
现在让我们使用 text-align 属性将 div 中的文本水平居中 -
<!DOCTYPE html>
<html>
<head>
<title>Align Horizontally</title>
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<style>
.demo {
background-color: orange;
border: 3px solid yellow;
text-align: center;
}
</style>
</head>
<body>
<h1>Software Quality Management</h1>
<p>Software Quality Management ensures the required level of software quality is achieved.
</p>
<div class="demo">
<p>This text in div is centered horizontally.</p>
</div>
</body>
</html>
要将 div 中的文本水平居中,请使用 justify-content 属性。现在让我们看一个例子
<!DOCTYPE html>
<html>
<head>
<title>Align Horizontally</title>
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<style>
.demo {
background-color: orange;
border: 3px solid yellow;
display: flex;
justify-content: center;
}
</style>
</head>
<body>
<h1>Software Quality Management</h1>
<p>Software Quality Management ensures the required level of software quality is achieved.
</p>
<div class="demo">
<p>This text in div is centered horizontally.</p>
</div>
</body>
</html>
要将 div 中的文本垂直居中,请使用 padding 属性。 padding 属性允许您指定元素的内容与其边框之间应出现多少空间。以下 CSS 属性可用于控制列表。您还可以使用以下属性为框每一侧的填充设置不同的值 -
现在让我们看一个使用 padding 属性在 div 中垂直居中文本的示例 -
<!DOCTYPE html>
<html>
<head>
<title>Align Vertically</title>
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<style>
.demo {
background-color: orange;
border: 3px solid yellow;
padding: 50px 0;
}
</style>
</head>
<body>
<h1>Software Quality Management</h1>
<p>Software Quality Management ensures the required level of software quality is achieved.
</p>
<div class="demo">
<p>This text in div is centered vertically.</p>
</div>
</body>
</html>
要将 div 中的文本垂直居中,请使用 line-height 属性。 line-height 属性修改组成一行文本的行内框的高度。
以下是可能的值 -
正常 - 指示浏览器将元素中的行高设置为“合理”距离。
number - 元素中行的实际高度是该值乘以元素的字体大小。
length - 元素中行的高度是给定的值。
百分比 - 元素中行的高度按元素字体大小的百分比计算。
现在让我们看一个使用 line-height 属性在 div 中垂直居中文本的示例 -
<!DOCTYPE html>
<html>
<head>
<title>Align Vertically</title>
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<style>
.demo {
background-color: orange;
border: 3px solid yellow;
line-height: 150px;
height: 200px;
}
</style>
</head>
<body>
<h1>Software Quality Management</h1>
<p>Software Quality Management is a process that ensures the required level of software
quality is achieved.</p>
<div class="demo">
<p> This text in div is centered vertically.</p>
</div>
</body>
</html>
以上就是如何将文本(水平和垂直)居中在一个div块内?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号