在我們開發前端頁面的時候,為了讓頁面效果美觀,會出現需要垂直居中效果的地方。下面本篇就讓我們來了解一下用css設置文字垂直居中的方法,希望對大家有所幫助。

方法1:使用line-height屬性使文字垂直居中
line-height屬性設置行間的距離(行高);該屬性不允許使用負值。
line-height屬性會影響行框的布局。在應用到一個塊級元素時,它定義了該元素中基線之間的最小距離而不是最大距離。
line-height 與 font-size 的計算值之差(在 CSS 中成為“行間距”)分為兩半,分別加到一個文本行內容的頂部和底部。可以包含這些內容的最小框就是行框。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>css 垂直居中</title>
<style>
.box{
width: 300px;
height: 300px;
background: #ddd;
line-height:300px;
}
</style>
</head>
<body>
<div class="box">css 垂直居中了--文本文字</div>
</body>
</html>
效果圖:

方法2:將外部塊格式化為表格單元格
表格單元格的內容可以垂直居中,將外部塊格式化為表格單元格就可垂直居中文本。
示例:將段落置於具有特定給定高度的塊內
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>css 垂直居中</title>
<style>
.box{
width: 400px;
height: 200px;
background: #ddd;
display: table-cell;
vertical-align: middle;
}
</style>
</head>
<body>
<div class="box">css 垂直居中了--文本文字</div>
</body>
</html>
效果圖:

方法3:使用CSS3的flex布局 使文字垂直居中
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>css 垂直居中</title>
<style>
.box{
width: 300px;
height: 200px;
background: #ddd;
/*設置為伸縮容器*/
display: -webkit-box;
display: -moz-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
/*垂直居中*/
-webkit-box-align: center;/*舊版本*/
-moz-box-align: center;/*舊版本*/
-ms-flex-align: center;/*混合版本*/
-webkit-align-items: center;/*新版本*/
align-items: center;/*新版本*/
}
</style>
</head>
<body>
<div class="box">css 垂直居中--文本文字(彈性布局)</div>
</body>
</html>
效果圖:

以上就是css文字如何垂直居中?的詳細內容,更多請關注html中文網其它相關文章!
