聊一聊居中实现方式

542 阅读2分钟

绝对定位元素设置水平居中

需求:

有时页面内的一些容器需要定位在特定的某个位置,但是需要容器在水平方向上面居中显示,比如 页面内的一个背景图里面放置一个容器,使用margin-top不方便,就决定使用绝对定位来设置。

实现方法:

  1. 方法一、知道容器尺寸的前提下
.element {
    width: 600px; height: 400px;
    position: absolute; 
    left: 50%; 
    top: 50%;
    margin-top: -200px;    /* 高度的一半 */
    margin-left: -300px;    /* 宽度的一半 */
}

缺点:该种方法需要提前知道容器的尺寸,否则margin负值无法进行精确调整,此时需要借助JS动态获取。

  1. 方法二、容器尺寸未知的前提下,使用CSS3的transform属性代替margin,transform中的translate偏移的百分比值是相对于自身大小的,设置示例如下:
.element {
    position: absolute; 
    left: 50%; 
    top: 50%;
    transform: translate(-50%, -50%); /* 50%为自身尺寸的一半 */
    -webkit-transform: translate(-50%, -50%);
}

缺点:兼容性不好,IE10+以及其他现代浏览器才支持。中国盛行的IE8浏览器被忽略是有些不适宜的(手机web开发可忽略)。

  1. 方法三、margin: auto实现绝对定位元素的居中
.element {
    width: 600px; height: 400px;
    position: absolute;
    left: 0; 
    top: 0; 
    right: 0; 
    bottom: 0;
    margin: auto;  /* 有了这个就自动居中了 */
}

flex布局

  1. 使用flex布局设置居中。容器设置 display: flex; align-items: center; justify-content: center;

  2. 使用flex 时也能通过给子项设置margin: auto实现居中。给容器设置 display: flex; 子项设置 margin: auto;

grid布局

  1. 使用grid设置居中。给容器设置 display: grid; align-items: center; justify-content: center;

  2. 使用grid时还能通过给子项设置margin: auto实现居中。给容器设置 display: grid; 子项设置 margin: auto;

tabel-cell

使用tabel-cell实现垂直居中。容器设置 display: table-cell; vertical-align: middle。孩子如果是块级元素,直接使用左右margin等于auto实现水平居中。如果是行内元素,给容器设置text-align: center;

还有一种不常用的方法实现垂直居中。给容器加给伪元素,设置line-height等于容器的高度。给孩子设置display: inline-block;

举个栗子:

<div class="box">
  <div class="child">hello</div>
</div>

<style>
.box {
  width: 200px;
  height: 200px;
  border: 1px solid;
  text-align: center;
}
.box::after {
  content: "";
  line-height: 200px;
}
.child {
  display: inline-block;
  background: red;
}
  
</style>

ps:还有很多其他奇葩的方式没有列举,最近一直在进行项目的学习又断更了,今天休息时正好复习了一下之前的知识顺便总结了一下,等项目弄好了来和大家分享一下我的项目,嘿嘿,加油