HTML — 父元素高度百分比时,文字如何垂直居中

233 阅读1分钟

在HTML中,想让某个容器内的文字实现水平且垂直居中,只需要对容器进行CSS样式的设计

水平居中可以使用text-aling:center

垂直居中可以使用line-height:容器的高度

例如:

HTML

<body>
    <div class="content">
        <div class="con_text">今天星期二</div>
    </div>
</body>

CSS

<style type="text/css">
    .content {
        height: 100px;
        width: 100%;
        background-color: aquamarine;
        text-align: center;
        line-height: 100px;
    }
</style>

全部代码

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			.content {
				height: 100px;
				width: 100%;
				background-color: aquamarine;
				text-align: center;
				line-height: 100px;
			}

			.con_text {}
		</style>
	</head>
	<body>
		<div class="content">
			<div class="con_text">今天星期二</div>
		</div>
	</body>
</html>

效果图

image.png

从代码和效果图中可以看到,在父容器content的高度为固定px值时,可以设置父容器的text-aling和line-height,使得其中的子元素实现水平且垂直居中

但是在高度为设置为百分比的情况,如果依旧使用 ling-height:容器高度的方法,则无法使文字准确的呈现垂直居中的状态

修改content的高度为20%,且设置body,html的高度为100%

<!DOCTYPE html>
<html style="height: 100%;">
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			.content {
				height: 20%;
				width: 100%;
				background-color: aquamarine;
				text-align: center;
				line-height: 100px;

			}

			.con_text {}
		</style>
	</head>
	<body style="height: 100%;">
		<div class="content">
			<div class="con_text">今天星期二</div>
		</div>
	</body>
</html>

效果图

image.png

可以看到,这时的line-height无法取得一个准确的数值来实现子元素的垂直居中

解决方法:

给父容器content设置 display:table

给需要垂直居中的子元素con_text设置 vertical-aling:middle;display:table-cell

效果图

image.png