css使用技巧(1)-元素居中

css元素居中是个永恒的话题,随着前端技术的进一步发展,实现方式也是愈来愈多,这里讲几个实用且高效的方式:

1、 水平居中

  • 1、 行内(内联)元素: text-align: center;

    1
    2
    3
    .parent{
    text-align: center;
    }
  • 2、 块级元素:margin: xpx auto; (子元素需设置宽度)

    1
    2
    3
    4
    .child{
    width: 200px;
    margin: 0 auto;
    }
  • 3、 flex布局: 子元素为内联元素

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    	
    .parent{
    display: flex;
    justify-content: center;
    }

    ```

    * 4、 flex布局: 子元素为块级元素(子元素无需设置宽度)

    ``` bash

    .parent{
    display: flex;
    }

    .child{
    margin: 10px auto;
    }

    ```

    ### 2、 垂直居中

    * 1、 行内(内联)元素: height = line-height

    ``` bash

    .parent{
    height: 200px;
    line-height: 200px;
    }
  • 2、 块级元素: 绝对定位(子元素尺寸需确定, margin负值实现位移)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15

    .parent{
    position: relative;
    height: 300px;
    }

    .child{
    width: 50px;
    height: 40px;
    position: absolute;
    left: 50%;
    right: 50%;
    margin-top: -20px;
    margin-right: -25px;
    }
  • 3、 块级元素: 绝对定位(子元素尺寸需确定, margin: auto)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    	
    .parent{
    position: relative;
    height: 300px;
    }

    .child{
    width: 50px;
    height: 50px;
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    margin: auto;
    }

    ```

    * 4、 块级元素: 绝对定位(子元素尺寸无需确定, transform位移)

    ``` bash

    .parent{
    position: relative;
    height: 300px;
    }

    .child{
    position: absolute;
    left: 50%;
    right: 50%;
    transform: translate(-50%,-50%);
    }
  • 5、 flex布局,子元素为块级元素,父元素display: flex; 子元素margin: auto;

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    	
    .parent{
    display: flex;
    width: 500px;
    height: 500px;
    }

    .child{
    margin: auto 10px;
    }

    ```

    * 6、 flex布局, 子元素为内联元素,父级元素display: flex;

    ``` bash

    .parent{
    display: flex;
    width: 500px;
    height: 500px;
    align-items: center;
    }
原创技术分享,您的支持将鼓励我继续创作