方法一、用before伪元素、inline-block、vertical-align实现
该方法适用于居中内容高度未知的情况
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.wrap{
text-align:center;
background:green;
height:200px;
}
.wrap:before{
content:'';
vertical-align:middle;
display:inline-block;
height:100%;
}
.content{
width:400px;
border:1px solid #ccc;
display:inline-block;
vertical-align:middle;
}
</style>
</head>
<body>
<div class="wrap">
<div class="content">
css设置内容垂直水平居中
</div>
</div>
</body>
效果图
方法二、用相对绝对定位和负边距实现上下左右居中
该方法适用于内容高度宽度已知的情况
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.wrap{
text-align:center;
background:green;
height:500px;
position:absolute;
}
.content{
width:400px;
height:200px;
top:50%;
left:50%;
position:relative;
border:1px solid #ccc;
margin: -100px 0 0 -200px;
}
</style>
</head>
<body>
<div class="wrap">
<div class="content">
css设置内容垂直水平居中
</div>
</div>
</body>
利用相对定位设置top和left为50%使content左上角位于wrap中心,再利用负边距使content居中,上边距为负的content高度的一半,右边距为负的content宽度的一半
效果图
方法三、用绝对定位来实现居中
适合高度、宽度已知的情况
.wrap{
background:green;
text-align: center;
height: 400px;
background: #4dc71f;
position: relative;
}
.content{
position: absolute;
margin: auto;
top: 0;
right: 0;
left:0;
bottom: 0;
width:400px;
height:200px;
border:1px solid #ccc;
}
效果图
方法四、用table-cell和inline-block实现水平垂直居中
.wrap{
background:green;
display: table-cell;
text-align: center;
vertical-align: middle;
height: 300px;
}
.content{
display: inline-block;
border:1px solid #ccc;
}
方法五、用css3中的transform实现水平垂直居中
.wrap{
background:green;
position:relative;
height: 300px;
}
.content{
position:absolute;
top:50%;
left:50%;
transform:translate(-50%,-50%);
border:1px solid #ccc;
}
效果图
方法六、flexbox实现水平垂直居中
.wrap{
background:green;
display:flex;
justify-content:center;
align-items:center;
height: 300px;
}
.content{
border:1px solid #ccc;
}
效果图