在实际的项目开发中我们经常遇到需要居中的问题。包括水平方向和垂直方向。总结一下遇到的居中问题。
1.元素块水平居中。
方法一:margin:0 auto
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
body {
background: #ccc;
}
.center-element {
width: 50%;
height: 300px;
background: #ddd;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="center-element">我需要居中</div>
</body>
</html>
方法二:transformX(-50%)
注:有些人可能不是很理解这个,transform后面的数值是元素大小的50%. 负值就是向左偏移自身的50%.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
body {
background: #ccc;
position: relative;
}
.center-element {
position: absolute;
left: 50%;
width: 50%;
height: 300px;
transform: translateX(-50%);
background: red;
}
</style>
</head>
<body>
<div class="center-element">我需要居中</div>
</body>
</html>
方法三:display:inline-block;text-align:center;
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
body {
background: #ccc;
text-align: center;
}
.center-element {
display: inline-block;
width: 50%;
height: 300px;
background: red;
}
</style>
</head>
<body>
<div class="center-element">我需要居中</div>
</body>
</html>
2.水平垂直居中
方法一:使用table的属性vertical-align,text-align。这个的使用比较多,功能计较强大。可以设置内部要显示内容为inline-block。实现文字元素之外的垂直居中。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.outer-container {
height: 500px;
background: blue;
width: 100%;
display: table;
}
.center-element {
display: table-cell;
width: 50%;
background: red;
vertical-align: middle;
text-align: center;
}
.no-center-element {
display: table-cell;
width: 50%;
background: green;
}
.table-row {
display: table-row;
height: 100%;
width: 100%;
}
</style>
</head>
<body>
<div class="outer-container">
<div class="table-row">
<div class="center-element">
我需要水平垂直居中</div>
<div class="no-center-element">
我不动</div>
</div>
</div>
</body>
</html>
方法二:使用transform,这种方法简单高大上,css3元素。不过要注意兼容。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.container {
background: blue;
position: relative;
height: 600px;
}
.center-element {
position: absolute;
left: 50%;
top: 50%;
width: 50%;
height: 200px;
transform: translate(-50%, -50%);
background: red;
}
</style>
</head>
<body>
<div class="container">
<div class="center-element">我需要水平垂直居中</div>
</div>
</body>
</html>
方法三:使用height: calc(….);计算,不推荐。