L - 居中布局

水平居中

先给出HTML结构布局

<div class="par">
        <div class="child">我是子元素</div>
    </div>

方法1. 将子元素转换为行内元素

.par{
        text-align: center;
    }
    .child{
        background-color: tomato;
            
        display:inline-block;
    }

将子元素设置为inline-block这样既能够像块元素同样设置盒模型,又能够像行内元素同样试用text-align:center进行居中flex

将子元素设置为inline-block后,子元素为块级元素,宽度为内容宽度code

方法2. 将子元素转换为table

.par{

    }
    .child{
        background-color: tomato;
            
        display:table;
        margin:0 auto;
    }

table元素是块级元素,宽度自适应为内容宽度,因此经过display:table对子元素进行转换并设置块元素居中标配margin:0 autoorm

方法3. 使用position+transform组合

.par{
        position: relative;
    }
    .child{
        background-color: tomato;
        width:300px;

        position: absolute;
        left:50%;
        transform: translateX(-50%);
    }

因为子元素是个块级元素(div),默认占满父元素宽度,因此咱们将子元素宽度设为300pxit

原理很简单,先用绝对定位将子元素置于距父元素左边界一半的位置,而后再将子元素向左移动自身的一半,达到居中效果io

注意,position:relative将父元素设为子元素绝对定位的参照物table

方法4. 利用flex布局的justify-content

.par{
        display:flex;
        justify-content: center;
    }
    .child{
        background-color: tomato;
    }

因为flex-grow属性默认值为0,flex-basis属性默认值为auto,因此宽度为内容宽度(在没有设置指定值时,不然为指定值)form

顺便说一句,flex很强大class

垂直居中

高度为元素高度,就不指定具体值了原理

方法1. 父元素转换为table-ceil

.par{
        height:500px;

        display:table-cell;
        vertical-align:middle;
    }
    .child{
        background-color: tomato;
    }

子元素宽度为内容宽度,父元素宽度为子元素宽度

方法2. 利用position+transform组合

.par{
        height:500px;

        position: absolute;
    }
    .child{
        background-color: tomato;
        width:300px;
        
        position: absolute;
        top:50%;
        transform: translateY(-50%);
    }

不指定子元素宽度的话,子元素的内容将纵向展现

方法3. 使用flex布局的align-items

.par{
        height:500px;

        display:flex;
        align-items:center;
    }
    .child{
        background-color: tomato;
        width:300px;
    }

水平垂直居中

上述两种居中布局的结合

方法1. 使用inline-block+text-align+table-cell+vertical-align

.par{
        width:500px;
        height:500px;
        border:1px solid #ccc;

        text-align: center;
        display: table-cell;
        vertical-align: middle;
    }
    .child{
        background-color: tomato;
        width:300px;

        display:inline-block;
    }

方法2. 利用position+transform组合

.par{
        width:500px;
        height:500px;
        border:1px solid #ccc;

        position: relative;
    }
    .child{
        background-color: tomato;
        width:300px;

        position: absolute;
        left:50%;
        top:50%;
        transform: translate(-50%,-50%);
    }

方法3. 使用flex布局

.par{
        width:500px;
        height:500px;
        border:1px solid #ccc;

        display:flex;
        justify-content: center;
        align-items: center;
    }
    .child{
        background-color: tomato;
        width:300px;
    }

有问题欢迎提问,实践出真知

相关文章
相关标签/搜索