时间:2021-07-01 10:21:17 帮助过:45人阅读
前言
元素的垂直居中也是我们日常网页布局中经常会遇到的问题,本文主要给大家介绍了关于利用css设置元素垂直居中的解决方法,文中介绍了多种情况的多种解决方法,相信会对遇到这个问题的朋友们带来一定的帮助,下面话不多说了,来一起看看详细的介绍吧。
html代码:
- <p class="parent">
- <p class="child">Text here</p>
- </p>
既然设置子元素的垂直居中,那就要知道父元素的高度,才能知道这所谓的中在哪,对吧?就像你想在一段距离的中间位置站住,那你首先需要知道这段距离有多长,你才能知道中间位置在哪.
注意,我所有的百分比高宽,都是建立在html,body {width: 100%;height: 100%;}
这样的设置的基础之上的,如果你没有这样设置,.parent这个p的父元素又是body,body你又没有设置宽高,你就可能看不到效果,.parent这个p的高宽比是相对于它的父元素的,所以你在使用的时候需要确定.parent这个p的父元素设置了宽度和高度的.
(1) 行内文本垂直居中
css代码:
- .parent {
- height: 100px;
- border: 1px solid #ccc; /*设置border是为了方便查看效果*/
- }
- .child {
- line-height: 100px;
- }
(2) 行内非文本垂直居中(以img为例)
html代码:
- <p class="parent">
- <img src="image.png" alt="" />
- </p>
css代码
- .parent {
- height: 100px;
- border: 1px solid #ccc; /*设置border是为了方便查看效果*/
- }
- .parent img {
- //注意此时应该保证图片自身的高度或者你设置的高度小于父元素的200px的行高,不然你看不出来居中的效果.
- line-height: 100px;
- }
(3) 未知高度的块级元素垂直居中
html代码:
- <p class="parent">
- <p class="child">
- <!--.child的高度未知,父元素要有高度-->
- sddvsds dfvsdvds
- </p>
- </p>
第一种方法(不需要加padding):
css代码:
- .parent {
- width: 100%;
- height: 100%;
- position: relative;
- /*display: table;*/
- }
- .child {
- width: 500px;
- border: 1px solid #ccc; /*设置border是为了方便查看效果*/
- position: absolute;
- top: 50%;
- transform: translateY(-50%);
- }
第二种方法(不使用transform):
css代码:
- .parent {
- position: relative;
- width: 100%;
- height: 100%;
- }
- .child {
- width: 500px;
- border: 1px solid #ccc;
- position: absolute;
- top: 0;
- bottom: 0;
- left: 0;
- right: 0;
- height: 30%;
- margin: auto;
- }
第三种方法(需要加padding):
css代码:
- #parent {
- padding: 5% 0;
- }
- #child {
- padding: 10% 0;
- }
第四种方法:
(使用display: table,此种方法也适用于行内文本元素的居中):
css代码:
- .parent {
- width: 100%;
- height: 100%;
- display: table;
- }
- .child {
- display: table-cell;
- vertical-align: middle;
- }
第五种方法(flex布局,这里需要考虑兼容性奥!)
css 代码:
- .parent {
- width: 100%;
- height: 100%; /*这里一定要写高度奥!*/
- display: flex;
- align-items: center;
- justify-content: center;
- }
(4) 已知高度的块级元素垂直居中
html代码:
- <p class="parent">
- <p class="child">
- <!--.child的高度已知,父元素高度已知-->
- sddvsds dfvsdvds
- </p>
- </p>
css代码:
- #parent {
- height: 300px;
- }
- #child {
- height: 40px;
- margin-top: 130px; /*这个只为父元素的高度减去这个元素的高度除以二计算得到的*/
- border: 1px solid #ccc;
- }
以上就是我目前发现并亲自测试可行的一些方法,应该还有其他的方法
以上就是总结利用css设置元素垂直居中的详细内容,更多请关注Gxl网其它相关文章!