css让DIV元素或文字水平垂直居中的五种方法

时间:2017-10-25
元素或文字水平垂直居中是前端开发常见的需求。本文章向大家介绍css让元素或文字水平垂直居中的五种方法,需要的朋友可以参考一下。

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

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

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

实例:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>如何让元素或文字水平垂直居中</title>
<style>
.container {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translateX(-50%) translateY(-50%);
}
</style>
  </head>
<body class="container">
文字水平垂直居中

</body>
</html>

在线运行

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

html, body, .container {
    height: 100%;
}
.container {
    display: flex;
    align-items: center;
    justify-content: center;
}

实例:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>如何让元素或文字水平垂直居中</title>
<style>
html, body, .container {
    height: 100%;
}
.container {
    display: flex;
    align-items: center;
    justify-content: center;
}
</style>
  </head>
<body>
  <div class="container">
    文字水平垂直居中
  </div>

</body>

在线运行

方法三:使用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;
}

实例:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>如何让元素或文字水平垂直居中</title>
<style>
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;

</style>
  </head>
<body>
  <div class="parent">
    <div class="child">如何让元素或文字水平垂直居中</div>
  </div>

</body>
</html>

在线运行

方法四:line-height

.parent {
    height: 200px;
    width: 400px;
    text-align: center;
}
.parent > .child {
    line-height: 200px;
}

实例:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>如何让元素或文字水平垂直居中</title>
<style>
.parent {
    height: 200px;
    width: 400px;
    text-align: center;
    background:red;
}
.parent .child {
    line-height: 200px;
}
</style>
  </head>
<body>
  <div class="parent">
    <div class="child">如何让元素或文字水平垂直居中</div>
  </div>

</body>
</html>

在线运行