html设置div内容垂直居中,css让DIV元素或文字水平垂直居中的五种方法

div元素或文字水平垂直居中的5中方法

第一种方法:使用 top: 50%/left: 50%和translateX(-50%) translateY(-50%);具体代码如下:

.container {

position: absolute;

top: 50%;

left: 50%;

transform: translateX(-50%) translateY(-50%);

}

实例:

如何让元素或文字水平垂直居中

.container {

position: absolute;

top: 50%;

left: 50%;

transform: translateX(-50%) translateY(-50%);

}

文字水平垂直居中

方法二:使用display: flex; align-items: center; justify-content: center;属性

html, body, .container {

height: 100%;

}

.container {

display: flex;

align-items: center;

justify-content: center;

}

实例:

如何让元素或文字水平垂直居中

html, body, .container {

height: 100%;

}

.container {

display: flex;

align-items: center;

justify-content: center;

}

文字水平垂直居中

方法三:使用table-cell/vertical-align: middle

html, body {

height: 100%;

}

.parent {

width: 100%;

height: 100%;

display: table;

text-align: center;

}

.parent > .child {

display: table-cell;

vertical-align: middle;

}

实例:

如何让元素或文字水平垂直居中

html, body {

height: 100%;

}

.parent {

width: 100%;

height: 100%;

display: table;

text-align: center;

}

.parent .child {

display: table-cell;

vertical-align: middle;

} justify-content: center;

如何让元素或文字水平垂直居中

方法四:line-height

.parent {

height: 200px;

width: 400px;

text-align: center;

}

.parent > .child {

line-height: 200px;

}

实例:

如何让元素或文字水平垂直居中

.parent {

height: 200px;

width: 400px;

text-align: center;

background:red;

}

.parent .child {

line-height: 200px;

}

如何让元素或文字水平垂直居中