您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何使用CSS将文本垂直居中?

如何使用CSS将文本垂直居中?

您可以尝试以下基本方法

div {

  height: 100px;

  line-height: 100px;

  text-align: center;

  border: 2px dashed #f69c55;

}


<div>

  Hello World!

</div>

但是,它仅适用于一行文本,因为我们将行的高度设置为与包含框元素相同的高度。

这是垂直对齐文本的另一种方法。此解决方案适用于一行和多行文本,但仍需要一个固定高度的容器:

div {

  height: 100px;

  line-height: 100px;

  text-align: center;

  border: 2px dashed #f69c55;

}

span {

  display: inline-block;

  vertical-align: middle;

  line-height: normal;

}


<div>

  <span>Hello World!</span>

</div>

CSS只是通过设置的line-height等于其高度来<div>调整的大小,垂直居中对齐,然后使用来将inline- block设置为。然后,将的行高设置回正常,因此其内容将自然地在块内流动。<span>``<div>``<span>``vertical-align: middle``<span>

这是另一个选项,可能在不支持display: table和的display: table- cell较旧的浏览器(主要是InternetExplorer7)上不起作用。使用CSS我们模拟表的行为(因为表支持垂直对齐),并且HTML与第二个示例相同:

div {

  display: table;

  height: 100px;

  width: 100%;

  text-align: center;

  border: 2px dashed #f69c55;

}

span {

  display: table-cell;

  vertical-align: middle;

}


<div>

  <span>Hello World!</span>

</div>

此技术使用绝对定位的元素将top,bottom,left和right设置为0。在SmashingMagazine的CSS中的绝对水平和垂直居中中_ 对此进行了详细介绍。

div {

  display: flex;

  justify-content: center;

  align-items: center;

  height: 100px;

  width: 100%;

  border: 2px dashed #f69c55;

}


<div>

  <span>Hello World!</span>

</div>
CSS 2022/1/1 18:15:28 有511人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶