CSS如何实现元素的垂直居中
1.垂直水平居中的方法
1.1 定位+margin:auto
子绝父相。
.box1{
width: 300px;
height: 300px;
border: 1px solid #555555;
margin-left: 20px;
margin-top: 20px;
}
.box1>div{
width: 100px;
height: 150px;
background-color: #409eff;
}
//父元素
.box1{
position: relative;
}
//子元素
.box1>div{
position: absolute;
left: 0;
right:0;
top: 0;
bottom: 0;
margin: auto;
}
1.2 定位+margin:负值
子绝父相,无需知道父元素宽高 但需知道子元素宽高。
.box2{
width: 300px;
height: 300px;
border: 1px solid #555555;
margin-left: 20px;
margin-top: 20px;
}
.box2{
position: relative;
}
.box2>div{
width: 100px;
height: 150px;
background-color: #409eff;
position: absolute;
left: 50%;
top:50%;
margin-left:-50px;
margin-top: -75px;
}
1.3 定位+transfrom
子绝父相。
.box3{
position: relative;
}
.box3>div{
width: 100px;
height: 150px;
background-color: #409eff;
position: absolute;
left: 50%;
top:50%;
/*相对于自己的*/
transform: translate(-50%,-50%);
}
1.4 弹性盒子
.box{
display: flex;
justify-content: center;
align-items: center;
}
1.5 网格布局
.box4{
display: grid;
align-content: center;
justify-content: center;
}
.box4>div{
width: 100px;
height: 150px;
background-color: #409eff;
}
2.总结
2.1 行内元素的垂直水平居中
水平居中:
- 子元素
text-align:center; - 父元素:
display:flex;justify-content:center;
垂直居中:
- 单行文本:
height==line-height; - 多行文本:
display:table-cell;vertical-align:middle
2.2 块级元素的垂直水平居中
水平居中:
- 宽度固定时候:
margin:0 auto(先上下后左右); 绝对定位+left:50%+margin:负本身一半
垂直居中:
position:absolute+top+margin-topposition:absolute+top+transfromflexgrid
2.3 height和line-height的区别
- line-height:每一行文字的高度。如果文字换行,整个盒子(没设置高度height时候)会被撑大(行数*行高)
- height:盒子的高度,不会变
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
html,body{
margin: 0;
padding: 0;
}
div {
width: 100%;
height: 180px;
background-color: #d9534f;
line-height: 60px;
}
</style>
</head>
<body>
<div>
<span>撒急急急急急急急急急急急急急急急急急急急急急急急急啥刺激啊十几级是撒开始看卡死卡死卡死卡刷卡卡刷卡时凯撒凯撒看卡
f撒急急急急急急急急急急急急急急急急急急急急急急急急啥刺激啊十几级是撒开始看卡死卡死卡死卡刷卡卡刷卡时凯撒凯撒看卡
撒急急急急急急急急急急急急急急急急急急急急急急急急啥刺激啊十几级是撒开始看卡死卡死卡死卡刷卡卡刷卡时凯撒凯撒看卡</span>
</div>
</body>
</html>


7880

被折叠的 条评论
为什么被折叠?



