利用CSS让页面元素居中的方案

页面元素居中是我们开发过程中常遇到的问题,同时也是面试中经常被提及的问题,所以我们必须熟练掌握

初始样式

<style>
  .container {
    width: 500px;
    height: 500px;
    background-color: pink;
  }

  .inner {
    width: 200px;
    height: 200px;
    background-color: skyblue;
  }
</style>

<body>
  <div class="container">
    <div class="inner"></div>
  </div>
</body>

方案一:利用postiton定位

.container{
  position: relative;
}
.inner{
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  margin: auto;
}

方案二:利用margin和定位

.container{
  position: relative;
}
.inner{
  position: absolute;
  top: 50%;
  left: 50%;
  margin-left: -100px;
  margin-top: -100px;
}

方案三:利用CSS3的margin和transform

.container{
  position: relative;
}
.inner{
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%); /* 上下左右平移自身宽度的50% */
}

方案四:利用flex布局

传新版本:

.container{
  display: flex;
  justify-content: center; /* 水平(主轴)居中 */
  align-items: center; /* 垂直(侧轴)居中 */
}

旧版本:

.container{
  display: -webkit-box;
  -webkit-box-pack: center; /* 水平(主轴)居中 */
  -webkit-box-align: center; /* 垂直(侧轴)居中 */
}

四种方案的对比

  • 前三种方案都依靠定位来实现的,最后一种方案是依靠flex布局来实现的
  • 前两种方案只能针对已知宽高的元素进行居中地位
  • 后两种方案可以针对未知宽高对元素进行居中,但需要CSS3的支持
发布了48 篇原创文章 · 获赞 28 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/u012925833/article/details/89282181