css实现水平垂直居中的几种方式

栏目: IT技术 · 发布时间: 5年前

内容简介:梳理下平时常用css水平垂直居中方式~HTMLCSS

梳理下平时常用css水平垂直居中方式~

使用flex布局

HTML

<div>
  <div></div>
</div>

CSS

.box {
  width: 100vw;
  height: 500px;
  background: skyblue;

  display: flex;
  align-items: center;
  justify-content: center;
}

.child {
  width: 200px;
  height: 200px;
  background-color: deepskyblue;
}

利用flex的 alignItems:center 垂直居中, justifycontent:center 水平居中

利用相对定位和绝对定位的 margin:auto

HTML

<div>
  <div></div>
</div>

CSS

.box {
  width: 100vw;
  height: 500px;
  background: skyblue;

  position: relative;
}

.child {
  width: 200px;
  height: 200px;
  background-color: deepskyblue;

  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;
}

相对定位下,使用绝对定位将上下左右都设置为0,再设置 margin:auto 即可实现居中

利用相对定位和绝对定位,再加上外边距和平移的配合

HTML

<div>
  <div></div>
</div>

CSS

.box {
  width: 100vw;
  height: 500px;
  background: skyblue;

  position: relative;
}

.child {
  width: 200px;
  height: 200px;
  background-color: deepskyblue;

  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

相对定位下,使用绝对定位,利用 margin 偏移外容器的50%,再利用 translate 平移回补自身宽高的50%即可

利用 textAlignverticalAlign

HTML

<div>
  <div></div>
</div>

CSS

.box {
  width: 100vw;
  height: 500px;
  background: skyblue;

  text-align: center;
}

.box:after {
  content: "";
  display: inline-block;
  height: 100%;
  width: 0;
  vertical-align: middle;
}

.child {
  display: inline-block;
  vertical-align: middle;
}

利用 textAlign:center 实现行内元素的水平居中,再利用 verticalAlign:middle 实现行内元素的垂直居中,前提是要先加上伪元素并给设置高度为100%,用过 elementUI 的可以去看看其消息弹窗居中实现方式就是如此

其他

上面都是在未知外容器和自身宽高下实现水平垂直居中的,如果已知其宽高,可以有更多种简单的方式实现居中,其原理无非是利用绝对定位的top/left偏移、margin偏移、padding填充,在此就不分析了。还有就是单纯文字的居中利用 lineHeighttextAlign 即可实现。

欢迎到前端学习打卡群一起学习~516913974


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Series 60 应用程序开发

Series 60 应用程序开发

巴克 / 人民邮电出版社 / 2005-7 / 75.0

Series 60智能手机开发平台正掀起新一轮的移动服务浪潮。超过60%的手机生产商获得了Series 60平台的授权。Series 60移动应用开发平台拥有最大的用户群,从而成为智能手机市场的代表。诺基亚与EMCC软件公司合作,为C++程序员和软件设计师编撰了这本Series 60开发的权威指南。本书由诺基亚资深专家进行了全面审阅。本书内容涉及了开发过程的各个阶段,从设计、编程、测试、调试到部署......一起来看看 《Series 60 应用程序开发》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具