CSS文本设置

一、单行文本的居中

1.文字水平居中(text-align: center)

<div style="text-align: center;height: 200px;width: 300px;border: 1px solid red">你好呀</div>

2.文字垂直居中(line-height:200px;height: 200px;)行高与块高度一致

你好呀
![](https://img2022.cnblogs.com/blog/1419087/202208/1419087-20220819105153070-602477174.png)

二、多行文本的垂直居中

1、通过verticle-align:middle 实现 CSS垂直居中

通过vertical-align:middle 实现 CSS垂直居中是最常用的方法,但是vertical生效的前提是元素的元素是display: table-cell

<div style="height: 200px; width: 200px; background-color: #bfa; display: table-cell; vertical-align: middle;">你好呀</div>

2、通过display:flex实现CSS垂直居中。

随着越来越多浏览器兼容CSS中的flexbox特性,所以现在通过“display:flex”实现CSS水平居中的方案也越来越受青睐。
通过display:flex实现CSS垂直居中的方法是给父元素display:flex; 而子元素align-self:center;
这个跟CSS水平居中的原理是一样的,只是在flex-direction上有所差别,一个是row(默认值),另外一个是column。

<div style="height: 200px; width: 600px; border:1px solid; display: flex;">
  <div style="height: 100px; width: 100px; background-color: #bfa; align-self:center">你好1</div>
  <div style="height: 100px; width: 100px; background-color: #bfa; align-self:center">你好2</div>
  <div style="height: 100px; width: 100px; background-color: #bfa; align-self:center">你好3</div>
</div>

posted @ 2022-08-19 11:26  DeyouKong  阅读(73)  评论(0编辑  收藏  举报