天天看點

關于文字垂直居中的設定

我們在寫代碼的時候,總會遇到一個非常尴尬的問題。明明設定了居中,為什麼<span>标簽的文字還是沒有居中呢。如圖,附加代碼:

關于文字垂直居中的設定

代碼

<!DOCTYPE html>
<html>
<head>
	<title>文字垂直居中設定</title>
	<meta charset="utf-8">
	<style type="text/css">
		body{
			background-color:#18222B;
		}
		.box{
			width:150px;
			margin:0 auto;
		}
		span{
			display:block;
			width:150px;
			height:32px;
			text-align:center;
			background-color:#FFF;  
		        color:#000000;
		}
	</style>
</head>
<body>
	<div class="box">
		<span>文字垂直居中</span>
	</div>
</body>
</html>
           

    我們可以看到,紅色代碼明明已經設定了居中,為什麼<span>标簽還是沒有居中呢。

    經過分析,本人才知道,text-align:center,是指水準居中。

    那麼怎麼才能讓它垂直也居中呢,當查找了一些資料後,發現非常簡單。僅僅取消設定一下文字的行高和對應的<span>标簽的高度一樣就可以了。(line-height: 32px;)

    我們看一下設定好行高後的<span>标簽。

關于文字垂直居中的設定
css