frontend-document icon indicating copy to clipboard operation
frontend-document copied to clipboard

[CSS] [2021-01-14 更新] CSS方式实现一个不知道宽高的 div 居中都有哪几种方法?

Open jeddygong opened this issue 3 years ago • 1 comments

jeddygong avatar Jan 14 '21 15:01 jeddygong

方式一:flex 布局

<style>
    .box {
        width: 200px;
        height: 200px;
        border: 1px solid blue;
        position: relative;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .item {
        background: red;
    }
</style>
<div class="box">
    <div class="item">
        <h1 >宽高不定</h1>
    </div>
</div>

方式二: Position + transform

<style>
    .box {
        width: 200px;
        height: 200px;
        border: 1px solid blue;
        position: relative;
    }

    .item {
        background: red;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
    }
</style>
<div class="box">
    <div class="item">
        <h1>宽高不定</h1>
    </div>
</div>

方式三:position + margin

<style>
.box {
    width: 200px;
    height: 200px;
    border: 1px solid blue;
    position: relative;
}

.item {
    width: 50%;
    height: 50%;
    background: red;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
}
</style>
<div class="box">
    <div class="item">
        <h1>宽高不定</h1>
    </div>
</div>

方式四: Grid布局


jeddygong avatar Jan 14 '21 15:01 jeddygong