程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长


+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

如何使用CSS将文本垂直居中?[重复]

发布于2021-01-31 17:07     阅读(494)     评论(0)     点赞(11)     收藏(1)


我有一个<div>包含文本元素,我想对齐此<div>垂直中心的内容

这是我的<div>风格:

#box {
  height: 170px;
  width: 270px;
  background: #000;
  font-size: 48px;
  color: #FFF;
  text-align: center;
}
<div id="box">
  Lorem ipsum dolor sit
</div>

实现这个目标的最佳方法是什么?


解决方案


您可以尝试以下基本方法:

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>调整的大小,垂直居中对齐,并将<span>设置为inline-block 然后,将的行高设置回正常,因此其内容将自然地在块内流动。<div><span>vertical-align: middle<span>


模拟表显示

这是另一个选项,可能在不支持display: table和的display: table-cell较旧浏览器(主要是Internet Explorer 7)上不起作用使用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。在Smashing Magazine的CSS中的绝对水平和垂直居中中对此进行了详细说明

div {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100px;
  width: 100%;
  border: 2px dashed #f69c55;
}
<div>
  <span>Hello World!</span>
</div>




所属网站分类: 技术文章 > 问答

作者:黑洞官方问答小能手

链接:http://www.qianduanheidong.com/blog/article/121/0812f7a92f0867e65cfd/

来源:前端黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

11 0
收藏该文
已收藏

评论内容:(最多支持255个字符)