css 水平垂直居中

372 阅读1分钟

文本

单行文本水平垂直居中

// html
<div class="text">我是单行文本</div>

// css
.text {
    width: 100px; height: 100px;
    text-align: center; line-height: 100px;
}

多行文本水平垂直居中

// html
<div class="text">我是多行文本我是多行文本我是多行文本我是多行文本</div>

// css
.text {
    width: 100px; height: 100px;
    display: table-cell; text-align: center; vertical-align: middle;
}

块级元素

子元素固定宽高水平垂直居中

负margin

// html
<div class="center">
    <div class="margin"></div>
</div>

// css
.center {
    position: relative; background: red;
    width: 150px; height: 100px; 
}
.margin {
    position: absolute; top: 50%; left: 50%; background: green;
    width: 50px; height: 50px; margin: -25px 0 0 -25px;
}

4个0

// html
<div class="center">
    <div class="zero"></div>
</div>

// css
.center {
    position: relative; background: red;
    width: 150px; height: 100px; 
}
.zero {
    position: absolute; top: 0; right: 0; bottom: 0; left: 0;
    width: 50px; height: 50px; background: green;
}

子元素不定宽高水平垂直居中

tranform

// html
<div class="center">
    <div class="transform">不定宽高水平居中</div>
</div>

// css
.center {
    position: relative; background: red;
    width: 150px; height: 100px; 
}
.transform {
    position: absolute; top: 50%; left: 50%;
    background: green;
    transform: translate(-50%, -50%);
}

table-cell

// html
<div class="center table-cell">
    <div>不定宽高水平居中</div>
</div>

// css
.table-cell {
    display: table-cell; vertical-align: middle; text-align: center;
}

flex

// html
<div class="center flex">
    <div>不定宽高水平居中</div>
</div>

// css
.flex {display: flex;  justify-content: center; align-items: center;}