本文摘自PHP中文网,作者藏色散人,侵删。
竖直居中一个元素的方法:1、通过“line-height”属性对单行内联元素实现垂直居中;2、利用flex布局实现垂直居中;3、使用“absolute+负margin”实现块级元素垂直居中。
垂直居中
1.单行内联元素垂直居中
1 2 3 4 5 6 7 8 9 10 | <div id= "box" >
<span>单行内联元素垂直居中。</span>。
</div>
<style>
#box {
height: 120px;
line-height: 120px;
border: 2px dashed #f69c55;
}
</style>
|
2.多行内联元素垂直居中
①利用flex布局(flex)
利用flex布局实现垂直居中,其中flex-direction: column定义主轴方向为纵向。这种方式在较老的浏览器存在兼容性问题。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <div class = "parent" >
<p>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.</p>
</div>
<style>
.parent {
height: 140px;
display: flex;
flex-direction: column;
justify-content: center;
border: 2px dashed #f69c55;
}
</style>
|
②利用表布局(table)
利用表布局的vertical-align: middle可以实现子元素的垂直居中
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <div class = "parent" >
<p class = "child" >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.</p>
</div>
<style>
.parent {
display: table;
height: 140px;
border: 2px dashed #f69c55;
}
.child {
display: table-cell;
vertical-align: middle;
}
</style>
|
3 块级元素垂直居中
①使用absolute+负margin(已知高度宽度)
通过绝对定位元素距离顶部50%,并设置margin-top向上偏移元素高度的一半,就可以实现了。
1 2 3 4 5 6 7 8 9 10 11 12 | <div class = "parent" >
<div class = "child" >固定高度的块级元素垂直居中。</div>
</div>
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
height: 100px;
margin-top: -50px;
}
|
②使用absolute+transform
当垂直居中的元素的高度和宽度未知时,可以借助CSS3中的transform属性向Y轴反向偏移50%的方法实现垂直居中。但是部分浏览器存在兼容性的问题。
1 2 3 4 5 6 7 8 9 10 11 | <div class = "parent" >
<div class = "child" >未知高度的块级元素垂直居中。</div>
</div>
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
transform: translateY(-50%);
}
|
③使用flex+align-items
通过设置flex布局中的属性align-items,使子元素垂直居中。
1 2 3 4 5 6 7 | <div class = "parent" >
<div class = "child" >未知高度的块级元素垂直居中。</div>
</div>
.parent {
display:flex;
align-items:center;
}
|
④使用table-cell+vertical-align
通过将父元素转化为一个表格单元格显示(类似 <td> 和 <th>),再通过设置 vertical-align属性,使表格单元格内容垂直居中。
1 2 3 4 5 6 7 8 9 | <div class = "parent" >
<div class = "child" >Demo</div>
</div>
<style>
.parent {
display: table-cell;
vertical-align: middle;
}
</style>
|
推荐学习:《前端视频》
以上就是如何竖直居中一个元素的详细内容,更多文章请关注木庄网络博客!
相关阅读 >>
html标签中行内元素和块级元素详解
css实现元素横向滚动的方法
css如何设置元素水平垂直居中显示
如何伸展一个元素到窗口高度
css如何禁止元素的点击事件
jquery怎么判断元素是否有某个属性
css实现隐藏元素效果
i、em、b、strong元素的使用详解
div设置width后超出父元素应该如何解决
html5学习笔记(二)-元素,属性,格式化具体介绍
更多相关阅读请进入《元素》频道 >>
人民邮电出版社
本书对 Vue.js 3 技术细节的分析非常可靠,对于需要深入理解 Vue.js 3 的用户会有很大的帮助。——尤雨溪,Vue.js作者
转载请注明出处:木庄网络博客 » 如何竖直居中一个元素