CSS 让元素水平垂直居中的好办法

一、行内元素(文字、图片等)水平垂直居中

1、行内元素水平居中

父容器设置:

text-align: center;

2、行内元素垂直居中

.father {

  height: 20px;

  line-height: 20px;

}

原理:让“文字高度”等于“盒子高度”即可。

二、块级元素水平垂直居中

1、绝对定位 + translate (无需指定子元素高度)

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        .father{
            position: relative;
            min-height: 500px;
            background: pink;
        }
        .son {
            position: absolute;
            background: red;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }
    </style>
</head>
<body>
    <div class="father">
        <div class="son">子元素的内容</div>
    </div>
    <script></script>
</body>
</html>
```

2、flex布局 (待改进)

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        .father{
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            background: pink;
        }
        .son {
            background: red;
        }
    </style>
</head>
<body>
    <div class="father">
        <div class="son">子元素的内容</div>
    </div>
    <script></script>
</body>
</html>

```

上面这种写法,不足之处在于:给父容器设置属性 `justify-content: center` 和 `align-items: center` 之后,导致父容器里的所有子元素们都垂直居中了(如果父容器里有多个子元素的话)。

3、flex布局 + margin:auto (推荐)

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        .father{
            display: flex;
            min-height: 100vh;
            background: pink;
        }
        .son {
            margin: auto;
            background: red;
        }
    </style>
</head>
<body>
    <div class="father">
        <div class="son">子元素的内容,想水平垂直居中</div>
        <div class="son2">这个元素不想水平垂直居中</div>
    </div>
    <script></script>
</body>
</html>
```

上面代码可是实现元素水平垂直居中

三、[七种方式实现垂直居中]  (https://jscode.me/t/topic/1936)

posted @ 2020-09-04 11:20  X_LLin  阅读(234)  评论(0编辑  收藏  举报