web中的文本居中

web中的文本居中

简要

首先要明白要想完成web中的居中,一般情况下是必须要设高度的,但也有特殊情况必须不设高度,了解这些我们就可以进行今天的分享了

首先

我们进行单行文本居中

下面由我来介绍我们要用的代码

height: 150px;
				/*实现垂直居中*/
				line-height: 150px;
				/*实现水平居中*/
				text-align: center;

实现单文本垂直居中就是将line-height的高度与行高一样

运行代码

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<style type="text/css">
			.r{
				background-color: red;
				height: 150px;
				/*实现垂直居中*/
				line-height: 150px;
				/*实现水平居中*/
				text-align: center;
			}
		</style>
	</head>
	<body>
		<p class="r">hello</p>
	</body>
</html>

运行效果图

局部截取_20260505_174458

多行文本居中

咱们进行多行文本居中所需代码

/*容器要给高度*/
				height: 120px;
				display: flex;
				/*多行文本居中*/
				align-items: center;
				/*水平居中*/
				justify-content: center;

运行代码

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<style type="text/css">
			.r{
				background-color: #FF0000;
				/*容器要给高度*/
				height: 120px;
				display: flex;
				/*多行文本居中*/
				align-items: center;
				/*水平居中*/
				justify-content: center;
			}
		</style>
	</head>
	<body>
		<p class="r">hello
		<br />
		hello</p>
	</body>
</html>

运行效果图

局部截取_20260506_164846

多行文本居中,方法二

这一次我们采用设置padding上下高度一样来实现的

注意:

这个方法不能给容器高度

所需代码

*用设置padding上下高度一样来实现*/
				padding-top: 40px;
				padding-bottom: 40px;

运行代码

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<style type="text/css">
			.r{
				background-color: #FF0000;
				/*用设置padding上下高度一样来实现*/
				padding-top: 40px;
				padding-bottom: 40px;
			}
		</style>
	</head>
	<body>
		<p class="r">hello
		<br />
		hello</p>
	</body>
</html>

效果图

局部截取_20260506_164912

posted @ 2026-05-07 08:40  寐式  阅读(7)  评论(0)    收藏  举报