美文网首页
让 div 居中的几种方式

让 div 居中的几种方式

作者: bestCindy | 来源:发表于2020-09-17 16:27 被阅读0次
<div class="parent">
    <div class="child"></div>
</div>

flex

元素宽度已知

<style>
    .parent {
        width: 300px;
        height: 300px;
        border: 2px solid red;

        display: flex;
        justify-content: center;
        align-items: center;
    }
    .child {
        width: 100px;
        height: 100px;
        border: 2px solid green;
    }
</style>

position(一)

元素宽度已知

<style>
    .parent {
        width: 300px;
        height: 300px;
        border: 2px solid red;

        position: relative;
    }
    .child {
        width: 100px;
        height: 100px;
        border: 2px solid green;

        position: absolute;
        left: 50%;
        top: 50%;
        margin: -50px 0 0 -50px;
    }
</style>

position(二)

元素宽度已知

<style>
    .parent {
        width: 300px;
        height: 300px;
        border: 2px solid red;

        position: relative;
    }
    .child {
        border: 2px solid green;
        width: 100px;
        height: 100px;

        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        margin: auto;
    }
</style>

position transform

元素宽度未知

<style>
    .parent {
        width: 300px;
        height: 300px;
        border: 2px solid red;

        position: relative;
    }
    .child {
        width: 100px;
        height: 100px;
        border: 2px solid green;

        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);    
    }
</style>

参考文章: https://juejin.im/post/6844903821529841671

相关文章

网友评论

      本文标题:让 div 居中的几种方式

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