元素居中

2023-06-25  本文已影响0人  xueyueshuai

方式1 display:flex

        display: flex;
        justify-content: center;
        align-items: center;

方式2 position:fixed;

<style>
    .ele {
        width: 300px;
        height: 300px;
        background: red;

        position: fixed;
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
        margin: auto;
    }
</style>
<div class="ele"></div>

方式3 position: absolute;

<style>
    .ele {
        width: 300px;
        height: 300px;
        background: red;

        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%); // 如果知道元素 宽高 此处用margin-top:-150px ...也可代替
    }
</style>
<div class="ele"></div>

方式4 display:table;

父级元素:{ display:table;}
子级元素: { display:table-cell;vertical-align:middle }
上一篇 下一篇

猜你喜欢

热点阅读