单行文字居中,多行文字靠左,需要css布局来实现,那么就需要用到两层元素,外面一层设置text-align:center;里面一层为行元素,需要设置text-align:left;这样有一行的时候因为里面是行内元素,有多少内容就多宽,而外面一层设置了text-align:center;所以会实现居中,当文字为多行的时候,由于本身设置了text-align:left,所以又会靠左显示。具体实现如下:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>标题</title>
<meta name="keywords" content="">
<meta name="description" content="">
<style>
div{
text-align:center;
}
p,span{
display:inline-block;
text-align:left;
}
</style>
</head>
<body>
<div>
<p>
单行居中多行靠左
</p>
<p>
单行居中多行靠左单行居中多行靠左单行居中多行靠左单行居中多行靠左单行居中多行靠左单行居中多行靠左单行居中多行靠左单行居中多行靠左单行居中多行靠左单行居中多行靠左单行居中多行靠左单行居中多行靠左
</p>
<span>单行居中多行靠左单行居中多行靠左单行居中多行靠左单行居中多行靠左单行居中多行靠左单行居中多行靠左单行居中多行靠左单行居中多行靠左单行居中多行靠左单行居中多行靠左单行居中多行靠左单行居中多行靠左</span>
</div>
</body>
</html>
这里需要注意的是:text-align:center的用法,在span中设置text-align:center是没有作用的,因为text-align的作用就是:可以为文字和内联元素、行内块设置水平居中,即使该文字是在块元素内。
所以span标签是需要设置display:inline-block,这样是行内块,当文字很短的时候不是独占一行的,所以父元素设置text-align:center的时候可以实现居中,当文字很多的时候,假如多行文字并且有半行存在的时候,因为是行内块,所以text-align:left起到了作用就多行文字靠左显示了。