竖直居中一个元素的方法:1、通过“line-height”属性对单行内联元素实现垂直居中;2、利用flex布局实现垂直居中;3、使用“absolute+负margin”实现块级元素垂直居中。
垂直居中
1.单行内联元素垂直居中
单行内联元素垂直居中。。#box { height: 120px; line-height: 120px; border: 2px dashed #f69c55; }
登录后复制
2.多行内联元素垂直居中
①利用flex布局(flex)
利用flex布局实现垂直居中,其中flex-direction: column定义主轴方向为纵向。这种方式在较老的浏览器存在兼容性问题。
.parent { height: 140px; display: flex; flex-direction: column; justify-content: center; border: 2px dashed #f69c55; }Dance like nobody is watching, code like everybody is. Dance like nobody is watching, code like everybody is. Dance like nobody is watching, code like everybody is.
登录后复制
②利用表布局(table)
利用表布局的vertical-align: middle可以实现子元素的垂直居中
.parent { display: table; height: 140px; border: 2px dashed #f69c55; } .child { display: table-cell; vertical-align: middle; }The more technology you learn, the more you realize how little you know. The more technology you learn, the more you realize how little you know. The more technology you learn, the more you realize how little you know.
登录后复制
3 块级元素垂直居中
①使用absolute+负margin(已知高度宽度)
通过绝对定位元素距离顶部50%,并设置margin-top向上偏移元素高度的一半,就可以实现了。
.parent {position: relative;}.child {position: absolute;top: 50%;height: 100px;margin-top: -50px;}固定高度的块级元素垂直居中。
登录后复制
②使用absolute+transform
当垂直居中的元素的高度和宽度未知时,可以借助CSS3中的transform属性向Y轴反向偏移50%的方法实现垂直居中。但是部分浏览器存在兼容性的问题。
.parent {position: relative;}.child {position: absolute;top: 50%;transform: translateY(-50%);}未知高度的块级元素垂直居中。
登录后复制
③使用flex+align-items
通过设置flex布局中的属性align-items,使子元素垂直居中。
.parent { display:flex; align-items:center;}未知高度的块级元素垂直居中。
登录后复制
④使用table-cell+vertical-align
通过将父元素转化为一个表格单元格显示(类似
和
),再通过设置 vertical-align属性,使表格单元格内容垂直居中。.parent { display: table-cell; vertical-align: middle; }Demo
登录后复制
推荐学习:《前端视频》
以上就是如何竖直居中一个元素的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2955792.html