稍微有点css知识的人都知道,对于已知宽度高度的元素水平垂直居中很好实现。但对css不是很熟悉,想要让高度和宽度都不知道的元素水平和垂直都居中,可就没那么容易了。
其实通过css实现对未知高度和宽度的元素水平和垂直居中的方法还是很多的。
方法1:
把元素的display熟悉设置为table-cell,相当于把元素转为表格,然后通过表格的水平垂直居中方式来让元素居中。不过这种方法有个前提,需要把父元素的display属性设置为table,并且父元素的高度和宽度不能是未知的。如果父元素是body,且body的高度和宽度都是100%,则还要同时设置html的高度和宽度为100%。否者只能水平居中不能处置居中。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>未知宽高元素水平垂直居中</title>
</head>
<style>
.parent1{
display: table;
height:300px;
width: 300px;
background-color: #FD0C70;
}
.parent1 .child{
display: table-cell;
vertical-align: middle;
text-align: center;
color: #fff;
font-size: 16px;
}
</style>
<body>
<div class="parent1">
<div class="child">
<span>hello world-1</span><br>
<!--
<span>hello world-1</span><br>
<span>hello world-1</span><br>
-->
</div>
</div>
</body>
</html>
方法2:
思路:使用一个空标签span设置他的vertical-align基准线为中间,并且让他为inline-block,宽度为0
缺点:多了一个没用的空标签,display:inline-blockIE 6 7是不支持的(添加上:_zoom1; display:inline)。
当然也可以使用伪元素来代替span标签,不过IE支持也不好,但这是后话了
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>未知宽高元素水平垂直居中</title>
</head>
<style>
.parent2{
height:300px;
width: 300px;
text-align: center;
background: #2196f3;
}
.parent2 span{
display: inline-block;;
width: 0;
height: 100%;
vertical-align: middle;
zoom: 1;
*display: inline;
}
.parent2 .child{
display: inline-block;
color: #fff;
zoom: 1;
*display: inline;
}
</style>
<body>
<div class="parent2">
<span></span>
<div class="child">
心月IT博客<br>
心月IT博客<br>
心月IT博客<br>
</div>
</div>
</body>
</html>
</html>
方法3:
采用绝对定位的方式实现水平垂直居中
思路:子元素绝对定位,距离顶部 50%,左边50%,然后使用css3 transform:translate(-50%; -50%)
优点:高大上,可以在webkit内核的浏览器中使用
缺点:不支持IE9以下不支持transform属性
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>未知宽高元素水平垂直居中</title>
</head>
<style>
.parent3{
position: relative;
height:300px;
width: 300px;
background: #2196f3;
}
.parent3 .child{
position: absolute;
top: 50%;
left: 50%;
color: #fff;
transform: translate(-50%, -50%);
}
</style>
<body>
<div class="parent3">
<div class="child">心月IT博客</div>
</div>
</body>
</html>方法4:
思路:使用css3 flex布局
优点:简单 快捷
缺点:flex布局有兼容性问题
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>未知宽高元素水平垂直居中</title>
</head>
<style>
.parent4{
display: flex;
justify-content: center;
align-items: center;
width: 300px;
height:300px;
background: #2196f3;
}
.parent4 .child{
color:#fff;
}
</style>
<body>
<div class="parent4">
<div class="child">心月IT博客</div>
</div>
</body>
</html> 