垂直居中
- 用padding内填充方式垂直居中
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>1.垂直居中</title>
<!--用padding内填充方式进行垂直居中-->
<style>
*{
margin: 0;
padding: 0;
}
.father{
width: 500px;
height: 200px;
background: #000;
margin: auto;
padding:150px 0;/*(父高-子高)/2*/
}
.son{
width: 200px;
height: 200px;
background: red;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
</html>
复制代码
- 给父元素添加overflow:hidden;给子元素添加margin-top;(margin-top传递问题)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>3.垂直居中</title>
<!--给父元素添加overflow:hidden;给子元素添加margin-top(margin-top传递问题)-->
<style>
*{
margin: 0;
padding: 0;
}
.father{
width: 500px;
height: 500px;
margin: auto;
background: green;
overflow: hidden;
}
.son{
width: 200px;
height: 200px;
background: pink;
margin-top: 150px;/*margin-top传递问题,(父高-子高)/2就是margin-top的值*/
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
</html>
复制代码
- 用弹性布局,实现垂直居中
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>2.垂直居中</title>
<style>
/*用弹性布局实现垂直居中*/
*{
margin: 0;
padding: 0;
}
.father{
width: 500px;
height: 500px;
background: blue;
margin: auto;
display: flex;
align-items: center;
}
.son{
width: 200px;
height: 200px;
background: green;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
</html>
复制代码
- 给父元素添加display:table-cell;vertical-align:middle;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>4.垂直居中</title>
<!--给父元素添加display:table-cell;vertical-align:middle-->
<style>
*{
padding: 0;
margin: 0;
}
.father{
width: 500px;
height: 500px;
background: purple;
display: table-cell;/*处理垂直居中*/
vertical-align: middle;/*处理垂直居中*/
}
.son{
width: 200px;
height: 200px;
background: goldenrod;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
</html>
复制代码
- 给父元素 position:relative;给子元素 position: absolute;top:50%; margin-top:-高度/2
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>5.垂直居中</title>
<!--给父元素 position:relative;给子元素 position: absolute;top:50%; margin-top:-高度/2-->
<style>
*{
margin: 0;
padding: 0;
}
.father{
width: 500px;
height: 500px;
background: #000;
margin: auto;
position: relative;
}
.son{
width: 200px;
height: 200px;
background: blue;
position: absolute;
top: 50%;
margin-top: -100px;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
</html>
复制代码
- 给父元素添加了position:relative;给子元素添加position:absolute;top:50%;transform:translateY(-高度/2)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>6.垂直居中</title>
<style>
*{
margin: 0;
padding: 0;
}
.father{
width: 500px;
height: 500px;
background: #000;
margin: auto;
position: relative;
}
.son{
width: 200px;
height: 200px;
background: yellowgreen;
position: absolute;
top: 50%;
transform: translateY(-100px);
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
</html>
复制代码