CSS:垂直居中
1.使用table-cell+vertical-align
- 锐客网 .parent{
width:500px;
height: 400px;
background-color: greenyellow;
display:table-cell;
vertical-align: middle;
}
.child{
width:300px;
height:200px;
background-color:red;
}Demo
原理:通过将父框转化为一个表格单元格显示(类似
- 锐客网 .parent{
position:relative;
width:200px;
height:100px;
background-color:green;
}
.child{
width:50%;
height:50%;
background-color:red;
position:absolute;
top:50%;
transform:translateY(-50%);
}DEMO
原理:类似于水平居中时的absolute+transform原理; 3.使用flex+align-items
- 锐客网 .parent{
width:300px;
height:200px;
background-color: green;
display:flex;
align-items:center;
}
.child{
width:50%;
height:50%;
background-color:red;
}Demo
4.使用flex+flex-direction+justify-content
- 锐客网 .parent{
width:300px;
height:200px;
background-color:green;
display: flex;
flex-direction: column;
justify-content: center;
}
.child{
width:50%;
height:50%;
background-color:red;
}DEMO
5.使用absolute+margin负边距
- 锐客网 .parent{
width:300px;
height:200px;
background-color:green;
position:relative;
}
.child{
width:50%;
height:50%;
background-color:red;
position:absolute;
top:50%;
margin-top:-50px;
}DEMO
【CSS:垂直居中】缺点:需知道子元素宽,高;以及高的一半;
6.使用absolute+margin
- 锐客网 .parent{
width:300px;
height:200px;
background-color:green;
position:relative;
}
.child{
width:50%;
height:50%;
background-color:red;
position:absolute;
top:0;
bottom:0;
margin:auto;
}DEMO
7.使用padding
- 锐客网 .parent{
width:100%;
padding:100px 0;
}
.child{
width:50%;
height:100px;
background-color:red;
}DEMO
原理:设置父元素padding值上下一样,不能设置高度,这样子元素看起来是在中间;
推荐阅读
- 标签、语法规范、内联框架、超链接、CSS的编写位置、CSS语法、开发工具、块和内联、常用选择器、后代元素选择器、伪类、伪元素。
- 3.css浮动
- 建立垂直阅读才是最重要的
- 垂直农场101-室内农业入门知识
- css|我用css精灵图拼接了自己的英文名字,不会还有人不知道精灵图技术吧()
- css|css三角的做法及其案例
- css|css中元素的显示与隐藏
- CSS兼容性笔记
- 微信小程序____CSS篇之定位(position)及浮动(float)
- 18,页面优化