CSS水平居中/垂直居中的方法

1.translate(-50%,-50%)

用 position 加 translate translate(-50%,-50%) 比较奇特,百分比计算不是以父元素为基准,而是以自己为基准。

<style>
#container{
200px;
height:200px;
background-color:yellow;
position:relative;
}
#content{
left:50%; top:50%; 
transform:translate(-50%,-50%);
-webkit-transform:translate(-50%,-50%);
background-color:gray; color:white; position:absolute;
}
</style>
<div id="container"><div id="content">Hello World</div></div>

2.视口居中

内容元素:position: fixedz-index: 999,记住父容器元素 position: relative

.Absolute-Center.is-Fixed {
   50%;
  height: 50%;
  overflow: auto;
  margin: auto;
  position: fixed;
  top: 0; left: 0; bottom: 0; right: 0;
  z-index: 999;
}
原文地址:https://www.cnblogs.com/Rookie-upgrade/p/7444228.html