1、字体水平居中
在CSS中,可以使用text-align属性来让文字水平居中。text-align属性规定元素中的文本的水平对齐方式,设置值为center则可实现文本文字水平居中对齐。
text-align属性通过指定行框与哪个点对齐,从而设置块级元素内文本的水平对齐方式。通过允许用户代理调整行内容中字母和字之间的间隔,可以支持值 justify;不同用户代理可能会得到不同的结果。
text-align属性可以设置的值:
left:把文本排列到左边。默认值:由浏览器决定。
right:把文本排列到右边。
center:把文本排列到中间。
justify:实现两端对齐文本效果。
说明:text-align属性用于块级元素,但如果是行内元素,可以使用display:inline;或将其转换为块级元素,在使用text-align属性来居中对齐。
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>css 水平居中</title> <style> .box { width: 400px; height: 100px; background: #ddd; text-align:center; } </style> </head> <body> <div class="box">css 水平居中了--文本文字</div> </body> </html>
效果图:
2、字体垂直居中
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)、使用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>
效果图:
以上就是html+css字体如何居中?的详细内容,更多请关注0133技术站其它相关文章!