css实现水平垂直居中的几种方式

2018-09-14  本文已影响0人  _conquer_

以下:wp为父级,box 为子级

.wp {
   position: relative;
}
/* 如子元素为固定宽高,设置宽高分别为100px */
.box{
   width: 100px;
   height: 100px;
}

仅居中元素定宽高适用

.box {
    position: absolute;;
    top: 50%;
    left: 50%;
    margin-left: -50px;
    margin-top: -50px;
}
.box {
    position: absolute;;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
}
.box {
    position: absolute;;
    top: calc(50% - 50px);
    left: calc(50% - 50px);
}

居中元素不定宽高

.box {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
.wp {
    line-height: 300px;
    text-align: center;
    font-size: 0px;
}
.box {
    font-size: 16px;
    display: inline-block;
    vertical-align: middle;
    line-height: initial;
    text-align: left; /* 修正文字 */
}
<div class="wp">
    <div class="wp-inner">
        <div class="box">123123</div>
    </div>
</div>
/* 定位代码 */
.wp {
    writing-mode: vertical-lr;
    text-align: center;
}
.wp-inner {
    writing-mode: horizontal-tb;
    display: inline-block;
    text-align: center;
    width: 100%;
}
.box {
    display: inline-block;
    margin: auto;
    text-align: left;
}
.wp {
    display: table-cell;
    text-align: center;
    vertical-align: middle;
}
.box {
    display: inline-block;
}
.wp {
    display: flex;
    justify-content: center;
    align-items: center;
}
.wp {
    display: grid;
}
.box {
    align-self: center;
    justify-self: center;
}
上一篇 下一篇

猜你喜欢

热点阅读