CSS三种垂直居中的方法
本文主要介绍了三种方法实现垂直居中,主要实现的代码在有注释的地方!
1.使用table布局,这里居中了盒子,如果想使文本内容居中在盒子内部设置table布局:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id='container'>
<div id='box1'>
<p>盒子1</p>
</div>
<div id='box2'>
<p>盒子2</p>
</div>
<div id='box3'>
<p>盒子3</p>
</div>
</div>
</body>
</html>
<style>
#container {
height: 600px;
width: 600px;
background-color: bisque;
display: table-cell; //把大盒子设置为table布局
vertical-align: middle //垂直属性设置为居中
}
#box1 {
height: 100px;
width: 100px;
background-color: coral;
margin: 0 auto;//盒子水平居中
}
#box2 {
height: 100px;
width: 100px;
background-color: cornflowerblue;
margin: 0 auto;//盒子水平居中
}
#box3 {
height: 100px;
width: 100px;
background-color: darkgoldenrod;
margin: 0 auto;//盒子水平居中
}
</style>
2.设置行高=盒子高度,对盒子内的文本水平垂直居中,无法对盒子居中
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id='container'>
<div id='box1'>
<p>盒子1</p>
</div>
<div id='box2'>
<p>盒子2</p>
</div>
<div id='box3'>
<p>盒子3</p>
</div>
</div>
</body>
</html>
<style>
#container {
height: 600px;
width: 600px;
background-color: bisque;
}
#box1 {
height: 100px;
width: 100px;
background-color: coral;
line-height: 100px; //设置行高=盒子高
text-align: center //文本水平居中
}
#box2 {
height: 100px;
width: 100px;
background-color: cornflowerblue;
line-height: 100px; //设置行高=盒子高
text-align: center //文本水平居中
}
#box3 {
height: 100px;
width: 100px;
background-color: darkgoldenrod;
line-height: 100px; //设置行高=盒子高
text-align: center //文本水平居中
}
</style>
3.使用flex布局,推荐!简洁,高效~
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id='container'>
<div id='box1'>
<p>盒子1</p>
</div>
<div id='box2'>
<p>盒子2</p>
</div>
<div id='box3'>
<p>盒子3</p>
</div>
</div>
</body>
</html>
<style>
#container {
height: 600px;
width: 600px;
background-color: bisque;
display: flex; //设置flex布局
justify-content: center; //主轴内容居中
align-items: center //叉轴内容居中
}
#box1 {
height: 100px;
width: 100px;
background-color: coral;
//对里面的文本居中
display: flex;
justify-content: center;
align-items: center
}
#box2 {
height: 100px;
width: 100px;
background-color: cornflowerblue;
//对里面的文本居中
display: flex;
justify-content: center;
align-items: center
}
#box3 {
height: 100px;
width: 100px;
background-color: darkgoldenrod;
//对里面的文本居中
display: flex;
justify-content: center;
align-items: center
}
</style>