CSS中10中居中 div 的方法

25 阅读2分钟

原文出处,在此作为分享 🧐

文中从CSS的 position 属性、FlexboxGrid 三个方面来探索如何让一个 子div 实现相对 父div 居中。

实现效果:

image.png

页面基本结构样式

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>示例</title>
    <style>
      .parent {
        width: 200px;
        height: 200px;
        background-color: #b0e0e6;
      }
      .child {
        width: 100px;
        height: 100px;
        background-color: #66cdaa;
      }
    </style>
  </head>
  <body>
    <div class="parent">
      <div class="child"></div>
    </div>
  </body>
</html>

一、使用CSS的 position 属性实现 div 居中

1.1 使用 position: relative、absolute 以及 top、left 偏移值

.parent {
    position: relative;
}
.child {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

1.2 使用 position: relative 和 absolute, top、left、right 和 bottom 偏移值以及 margin: auto

.parent {
    position: relative;
}
.child {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
}

如果我们只设置了top: 0bottom: 0以及margin: auto,子元素就会垂直居中

同样,如果我们只设置了left: 0right: 0以及margin: auto,子元素就会水平居中

二、使用 CSS 中 Flexbox 实现 div 居中

2.1 使用Flexbox、 justify-content 和 align-item

.parent {
    display: flex;
    justify-content: center;
    align-items: center;
}

2.2 使用Flexbox、justify-content 和 align-self

.parent {
    display: flex;
    justify-content: center;
}
.child {
    align-self: center;
}

2.3 使用Flexbox 和 margin: auto

.parent {
    display: flex;
}
.child {
    margin: auto;
}

三、使用 CSS 中 Grid 实现 div 居中

3.1 使用 Grid、justify-content 和 align-items

.parent {
    display: grid;
    justify-content: center;
    align-items: center;
}

3.2 使用 Grid 和 place-items

.parent {
    display: grid;
    place-items: center;
}

3.3 使用Grid、align-self 和 justify-self

.parent {
    display: grid;
}
.child {
    justify-self: center;
    align-self: center;
}

3.4 使用 Grid 和 place-self

.parent {
    display: grid;
}
.child {
    place-self: center;
}

3.5 使用 Grid 和 margin: auto

.parent {
    display: grid;
}
.child {
    margin: auto;
}

如我们期望的那样,所有方法都会得到相同的结果:

image.png

总结

本文讨论了10种将 div 居中的方法,包括:

  1. 使用position: relativeabsolutetopleft偏移值
  2. 使用positionrelativeabsolutetopleft rightbottom偏移值和margin: auto
  3. 使用flexboxjustify-content、 align-item
  4. 使用flexboxjustify-contentalign-self
  5. 使用flexboxmargin: auto
  6. 使用grid justify-contentalign-items
  7. 使用gridplace-items
  8. 使用gridalign-selfjustify-self
  9. 使用gridplace-self
  10. 使用gridmargin: auto