本文摘自PHP中文网,作者藏色散人,侵删。
css实现文字垂直居中的方法:1、使用line-height属性使文字垂直居中;2、将外部块格式化为表格单元格;3、通过CSS3的flex布局使文字垂直居中。
本文操作环境:windows7系统、HTML5&&CSS3版、Dell G3电脑。
方法:
方法1:使用line-height属性使文字垂直居中
line-height属性设置行间的距离(行高);该属性不允许使用负值。
line-height属性会影响行框的布局。在应用到一个块级元素时,它定义了该元素中基线之间的最小距离而不是最大距离。
line-height 与 font-size 的计算值之差(在 CSS 中成为“行间距”)分为两半,分别加到一个文本行内容的顶部和底部。可以包含这些内容的最小框就是行框。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <!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:将外部块格式化为表格单元格
表格单元格的内容可以垂直居中,将外部块格式化为表格单元格就可垂直居中文本。
示例:将段落置于具有特定给定高度的块内
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <!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布局 使文字垂直居中
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | <!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>
|
效果图:
更多详细的HTML/CSS知识,请访问CSS视频教程栏目!
以上就是css文字如何垂直居中的详细内容,更多文章请关注木庄网络博客!
相关阅读 >>
css列表怎么横着排列
css样式怎么写在jsp中
css @font-face属性怎么用
利用css来画出各种样式不同的梯形
前端工程师需要掌握哪些知识?
css id选择器怎么写
css怎么合并单元格
html如何给段落加粗
css怎么设置显示隐藏动画
css怎么设置扇形区域
更多相关阅读请进入《css》频道 >>
人民邮电出版社
本书对 Vue.js 3 技术细节的分析非常可靠,对于需要深入理解 Vue.js 3 的用户会有很大的帮助。——尤雨溪,Vue.js作者
转载请注明出处:木庄网络博客 » css文字如何垂直居中