美文网首页
css布局-水平垂直居中的4种实现

css布局-水平垂直居中的4种实现

作者: 小麻烦爱学习 | 来源:发表于2020-05-14 18:16 被阅读0次

已知居中元素的宽度和高度

实现1

<style>
    #father {
        position: relative; /*关键*/
        width: 500px;
        height: 300px;
        background-color: lightcoral;
    }   
    #son {
        position: absolute;/*关键*/
        top: 0;/*关键*/
        left: 0;/*关键*/
        right: 0;/*关键*/
        bottom: 0;/*关键*/
        width: 100px;/*必须*/
        height: 100px;/*必须*/
        margin: auto;/*关键*/
        background-color: lightpink;
    }
</style>
    
<div id="father">
    <div id="son">块级元素</div>
</div>

实现2

<style>
    #father {
        position: relative; /*关键*/
        width: 500px;
        height: 300px;
        background-color: lightcoral;
    }   
    #son {
        position: absolute;/*关键*/
        top: 50%;/*关键*/
        left: 50%;/*关键*/
        width: 100px;/*必须*/
        height: 100px;/*必须*/
        margin-left: -50px;/*关键,width的一半*/
        margin-top: -50px;/*关键,height的一半*/
        background-color: lightpink;
    }
</style>
    
<div id="father">
    <div id="son">块级元素</div>
</div>

和第一种的区别:
子元素没有right:0;bottom:0;
margin:auto->margin-left:-50px;margin-top:-50px;

不需要关注居中元素的宽度和高度

实现1

<style>
    #father {
        position: relative; /*关键*/
        width: 500px;
        height: 300px;
        background-color: lightcoral;
    }
 
    #son {
        position: absolute;/*关键*/
        left: 50%;/*关键*/
        top: 50%;/*关键*/
        transform: translateX(-50%) translateY(-50%);/*关键*/
        background-color: lightpink; 
    }
</style>
    
<div id="father">
    <div id="son">块级元素</div>
</div>

使用css3的transform: translateX(-50%) translateY(-50%); 注意兼容问题

实现2

<style>
    #father {
        display: flex;/*关键*/
        justify-content: center;/*关键,子元素水平居中*/
        align-items: center;/*关键,子元素垂直居中*/
        width: 500px;
        height: 300px;
        background-color: lightcoral;
    }
    #son {
        background-color: lightpink;
    }
</style>
    
<div id="father">
    <div id="son">块级元素</div>
</div>

主要使用css3的flex布局,注意兼容问题

总结,一共有两大方式:
①父元素position:relative,子元素position:absolute
②使用flex布局

相关文章

网友评论

      本文标题:css布局-水平垂直居中的4种实现

      本文链接:https://www.haomeiwen.com/subject/wsrxohtx.html