Css实现盒子在网页内垂直居中的常用方式

image.png

将如图的盒子在页面内垂直水平居中的几种常用方式

  1. 定位法+margin(知道盒子实际宽高)
.box {
  width: 100px;
  height: 100px;
  background: blueviolet;
  position: absolute;
  left: 50%;
  top: 50%;
  margin-top: -50px;
  margin-left: -50px;
}
复制代码

2.定位+transform(无需知道盒子实际宽高)

.box {
  width: 100px;
  height: 100px;
  background: blueviolet;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%); 
}
复制代码

3.flex布局(父元素)

body {
  position: relative;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
}
.box {
  width: 100px;
  height: 100px;
  background: blueviolet;
}
复制代码

4.display: table-cell 无兼容性问题

.box {
  width: 100px;
  height: 100px;
  background: blueviolet;
  display: table-cell;
  text-align: center;
  vertical-align: middle;
}
复制代码

image.png

以上四种方式 都可以实现盒子水平居中 具体使用哪一种根据实际情况决定

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享