css中文字居中怎么设置?

在我们开发前端页面的时候,为了让页面效果美观,会出现需要垂直居中效果的地方。下面本篇文章就来给大家介绍一下使用CSS设置文本文字居中的方法,希望对大家有所帮助。

1、CSS设置文本文字水平居中

在CSS中可以使用text-align属性来设置文本文字水平居中。该属性规定元素中的文本的水平对齐方式,可以通过使用center值来设置文本居中。

语法:

text-align : left | right | center | justify

text-align参数值与说明:

  • left : 左对齐

  • right : 右对齐

  • center : 居中

  • justify : 两端对齐(不推荐使用,通常大部分浏览器不使用)

我们对text-align常用的参数值为left、right、center

示例:

<!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.jpg-600

2、CSS设置文本文字垂直居中

1、line-height属性 使文字垂直居中

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>css 垂直居中</title>
		<style>
			.box{
				width: 200px;
			    height: 200px;
			    background: #ddd;
			    line-height:200px;
			}
		</style>
	</head>
	<body>
		<div class="box">css 垂直居中了--文本文字</div>
	</body>
</html>

效果图:

3.jpg-600

这样就能让div中的文字水平垂直居中了

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>

效果图:

4.jpg-600

以上就是css中文字居中怎么设置?的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » CSS3 答疑