CSS: 居中

水平居中

flex 布局

.parent {
    display: flex;
    justify-content: center;
}

或者

.parent {
    display: flex;
    flex-direction: column;
    align-items: center;
}

内联元素

.parent {
    text-align: center;
}

margin

.children {
    margin: 0 auto;
}

position

.parent {
    position: relative;
}
.children {
    position: absolute;
    left: 50%;
    top: 0;
    transform: translateX(-50%);
}

table

过时,放弃

垂直居中

flex 布局

.parent {
    display: flex;
    align-items: center;
}

或者

.parent {
    display: flex;
    flex-direction: column;
    justify-content: center;
}

内联元素

.parent {
  height: 100px;
  line-height: 100px;
}

margin

必须设置父元素高度。

.parent {
    height: 100px;
}

.children {
    margin: auto 0;
}

position

.parent {
    position: relative;
}

.children {
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
}

猜你喜欢

转载自blog.csdn.net/weixin_33918114/article/details/87319330
今日推荐