CSS-常用元素垂直居中方法

54 阅读1分钟

居中元素宽高未知

image.png

1.flex布局

<style>
    .parent {   
        width: 300px;
        height: 300px;
        background-color: yellow;
        display: flex;   /* 父元素设置flex布局 */
        justify-content: center;
        align-items: center;
    }
    .son {
        background-color: pink;
    }
</style>

2.绝对定位 + tranform

    <style>
        .parent {
            width: 200px;
            height: 200px;
            background-color: yellow;
            position: relative;  /* 相对定位 */
        }
        .son {
            background-color: pink;
            position: absolute; /* 绝对定位 */
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);   /* 会将元素位移自己宽度和高度的-50% */
        }
    </style>

3.grid网格布局

    <style>
        .parent {
            width: 200px;
            height: 200px;
            background-color: yellow;
            display: grid;  /* 网格布局 */
            justify-content: center;
            align-items: center;      
        }
        .son {
            background-color: pink;
        }
    </style>

居中元素宽高已知

4.绝对定位 + margin:auto

margin的值为auto的具体含义:

  • auto意为自动填充。以margin:0,auto;为例,程序会自动计算剩余左右两部分的空白长度,把其等分再作为div左右的外边距。所以我们可以使用此行代码使得div居中。
  • margin:auto只能水平居中不能垂直居中:块级元素在默认情况下会占据整行空间,设置auto时,元素左右尚有空缺,可以看到居中效果,但上下已经没有空缺了
<style>
    .parent {
        width: 200px;
        height: 200px;
        background-color: yellow;
        position: relative;  /* 父盒子相对定位 */
    }
    .son {
        width: 100px;
        height: 100px;
        background-color: pink;
        position: absolute;  /* 子元素绝对定位 */
        left: 0;  /* 子元素外边距设置为0  四个定位属性的值设置为0,子盒子设置宽高,则显示图1(水平垂直居中)*/
        right: 0;
        top: 0;
        bottom: 0;
        margin: auto;   
    }
</style>

元素宽高未知情况下

    <style>
        .parent {
            width: 200px;
            height: 200px;
            background-color: yellow;
            position: relative;  /* 父盒子相对定位 */
        }
        .son {
            /* width: 100px;
            height: 100px; */
            background-color: pink;
            position: absolute;  /* 子元素绝对定位 */
            left: 0;  /* 子元素外边距设置为0  四个定位属性的值设置为0,子盒子没有设置宽高,则会被拉开到和父级一样宽高*/
            right: 0;
            top: 0;
            bottom: 0;
            margin: auto;   
        }
    </style>

image.png

补充:内联元素的居中

水平居中

  • 行内元素可设置:text-align: center
  • flex布局设置父元素:display: flex; justify-content: center

垂直居中

  • 单行文本父元素确认高度:height:line-height
  • 多行文本父元素确认高度:display: table-cell; vertical-align: middle

image.png

<head>
    <title>Document</title>
    <style>
        .parent {
            width: 200px;
            height: 200px;
            background-color: yellow;
            text-align: center;  /* 父元素设置 */
        }
    </style>
</head>
<body>
    <div class="parent">
        <span class="son">123</span>
    </div>
</body>