前端面試中最常問到的垂直水平居中問題

JoySang發表於2018-09-26

方法一、 CSS3 transform和position(元素寬高未知的情況)

<div class="box">
    <span>寬高未知</span>
</div>

.box {
    width: 400px;
    height: 400px;
    background: #ccc;
    position:relative;
}
.box span {
    background: red;
    position: absolute;
    left: 50%;
    top: 50%;
    color: #fff;
    transform: translate(-50%, -50%);
}
複製程式碼

前端面試中最常問到的垂直水平居中問題

方法二、 絕對定位和margin-left:-自身寬度一半,margin-top: -自身高度的一半 (已知寬高)

<div class="box">
    <span>寬高已知</span>
</div>

.box {
    width: 400px;
    height: 400px;
    background: #ccc;
    position: relative;
}
.box span {
    display: inline-block;
    width: 100px;
    height: 100px;
    background: red;
    text-align: center;
    line-height: 100px;
    position: absolute;
    left: 50%;
    top: 50%;
    color: #fff;
    margin-left: -50px;
    margin-top: -50px;
}
複製程式碼

前端面試中最常問到的垂直水平居中問題

方法三、 css3 flex佈局

<div class="box">
    <div class="child"></div>
</div>

.box {
    width: 400px;
    height: 400px;
    background: #ccc;
    display:flex;
    justify-content:center;
    align-items: center;
}
.box .child {
    display: inline-block;
    width: 100px;
    height: 100px;
    background: red;
}
複製程式碼

前端面試中最常問到的垂直水平居中問題

方法四、 被居中的元素是inline或者inline-block元素

<div class="box">
    <span class="child">inline和inline-block元素</span>
</div>

.box {
    width: 400px;
    height: 400px;
    background: #ccc;
    display: table-cell;
    text-align: center;
    vertical-align: middle;
}
.box .child {
    display: inline-block;
    width: 100px;
    height: 100px;
    background: red;
}
複製程式碼

前端面試中最常問到的垂直水平居中問題

方法五、絕對定位和margin:auto

<div class="box">
    <div class="child">定高</div>
</div>

.box {
    width: 400px;
    height: 400px;
    background: #ccc;
    position: relative;
}
.box .child {
    width: 100px;
    height: 100px;
    background: red;
    text-align: center;
    color: #fff;
    line-height: 100px;
    position: absolute;
    top:0;
    right:0;
    bottom:0;
    left:0;
    margin: auto;
}
複製程式碼

前端面試中最常問到的垂直水平居中問題

方法六、line-height: 父級高度和text-align: center

<div class="box">
    <span class="child">line-height</span>
</div>

.box {
    width: 400px;
    height: 400px;
    background: #ccc;
    line-height: 400px;
    text-align: center;
    font-size: 0;
}
.box .child {
    background: red;
    font-size: 14px;
    color: #fff;
}
複製程式碼

前端面試中最常問到的垂直水平居中問題

相關文章