CSS垂直居中几种方法

来源:互联网 发布:数据库嵌套not exists 编辑:程序博客网 时间:2024/05/18 03:59

垂直居中布局很常用到,自己总结下来以后用的话也很方便,算是对自己上网阅读资料的一个考核

1.不知道自己高度和父容器高度的情况下, 利用绝对定位只需要以下三行:
parentElement{        position:relative;    } childElement{        position: absolute;        top: 50%;        transform: translateY(-50%); }

2.若父容器下只有一个元素,且父元素设置了高度,则只需要使用相对定位即可

    parentElement{        height:xxx;    }    .childElement {      position: relative;      top: 50%;      transform: translateY(-50%);    }

3.Flex 布局:

不考虑兼容老式浏览器的话,用Flex布局简单直观一劳永逸:
parentElement{    display:flex;/*Flex布局*/    display: -webkit-flex; /* Safari */    align-items:center;/*指定垂直居中*/}
4,使用position:absolute,设置left、top、margin-left、margin-top的属性

.one{ //子元素
position:absolute;
width:200px;
height:200px;
top:50%;
left:50%;
margin-top:-100px;
margin-left:-100px;
background:red;
}

这种方法基本浏览器都能够兼容,不足之处就是需要固定宽高。
5,利用position:absolute属性,设置top/bottom/right/left

.four{ //子元素
position:absolute;
width:140px;
height:140px;
top:0;
right:0;
bottom:0;
left:0;
margin:auto;
background:black;
}
同上,不足之处需要固定垂直居中元素的宽高
6,最简单的一种使行内元素居中的方法,使用line-height属性

.six{
width:100px;
height:100px;
line-height:100px;
text-align:center;
background:gray;
}

这种方法也很实用,但是只限于单行文本

7.vertical-align: middle;只对行内元素有效,例如:

<div class="wrap">
<span class="null"></span>
<span class="in">是的撒大是是的撒所多多的身份丹凤巅峰是是的撒所多多的身份丹是是的撒所多多的身份丹</span>
</div>
css:
.in{
width: 90px;
display: inline-block;
vertical-align: middle;
}
.null{
height: 100%;
display: inline-block;
vertical-align: middle;
}
class="null的元素不能省略,就是因为空文本高度等于父元素的高度,然后垂直居中才能让同级元素居中,这个我理解不是很好,可以自行查资料。




原创粉丝点击