一、css如何实现垂直水平居中?
1.利用弹性布局(flex)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
padding: 0;
margin: 0;
}
.father {
display: flex;
/* 容器添加display:flex: */
justify-content: center;
/* 主轴设置居中 */
align-items: center;
/* 侧轴居中 */
width: 500px;
height: 500px;
background-color: pink;
}
.son {
width: 100px;
height: 100px;
background-color: skyblue;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
</html>
2.定位(position)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
padding: 0;
margin: 0;
}
.father {
position: relative;
width: 500px;
height: 500px;
background-color: pink;
}
.son {
/* 子绝父相 */
position: absolute;
top: calc(50% - 50px);
/* 先走最近一级带有定位的祖先元素的50%,(不包括static定位)再往回走自身高度的一半(50%) */
left: calc(50% - 50px);
width: 100px;
height: 100px;
background-color: skyblue;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
</html>
3.定位(position)和转换(transform)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
padding: 0;
margin: 0;
}
.father {
position: relative;
width: 500px;
height: 500px;
background-color: pink;
}
.son {
/* 子绝父相 */
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
/* 自身高宽不确定的情况下,可以使用位移translate,往回走50%,相对于自身的高宽 */
width: 100px;
height: 100px;
background-color: skyblue;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
</html>
4.margin
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
padding: 0;
margin: 0;
}
.son {
margin: calc(50% - 50px) calc(50% - 50px);
/* 设置margin 50% - 自身宽度的一半 */
/* 50% 指的是父盒子的50% */
width: 100px;
height: 100px;
background-color: skyblue;
}
</style>
</head>
<body>
<div class="son"></div>
</body>
</html>
二、清除浮动的方式
1.给父级设置双伪元素
给父级元素设置双伪元素;
<div class="container clearfix">
<div class="wrap">aaa</div>
</div>
.clearfix:after{
content:""; /*设置内容为空*/
height:0; /*高度为 0*/
line-height:0; /*行高为 0*/
display:block; /*将文本转为块级元素*/
visibility:hidden; /*将元素隐藏*/
clear:both; /*清除浮动*/
}
.clearfix{
zoom:1; /*为了兼容 IE*/
}