在前端布局中,不可避免的会让元素垂直水平居中,已达到某种效果,那么这个元素按照是否知道宽高来分为已知宽高,未知宽高
1.借助table的td中的元素
下面介绍的方法主要是利用display:inline-block;让元素变为行内块元素,利用vertical-align:middle来实现垂直居中,利用父元素的text-align:center;实现水平居中。
直接上例子吧
<!DOCTYPE html>
<html>
<head><style>
*{margin:0px; padding:0px;}
.wrap {
position:absolute;background-color:blue;width:100%;height:100%;text-align:center
}
.juzhong {
//下面这行要或者不要都可以,div是否有宽度和高度这种方法都可以
// width:200px;height:100px;
background-color:red;display:inline-block;
}
</style>
</head>
<body>
<table class='wrap' >
<tr>
<td><div class='juzhong' >hahhahaha</div></td></tr>
</table>
</body>
</html>
结果显示
其实上面这种方法说白了就是使得要居中的div变成table-cell包裹的元素,然后自己变为行级元素
<!DOCTYPE html>
<html>
<head><style>
*{margin:0px; padding:0px;}
.wrap {display:table-cell; width:300px; height:300px; text-align:center; vertical-align:middle; background:rgba(0,0,0,0.5);}
.test {background:red; display:inline-block;width:50px;height:50px;}
</style>
</head>
<body>
<div class="wrap">
<div class="test">
hah
</div>
</div>
</body>
</html>
结果如下:
2.另一种方法的是利用一个没有宽度b标签来实现水平垂直居中,但是很遗憾的是原理我没有搞懂,如果大家有明白的能否给我说下哈哈
<!DOCTYPE html>
<html>
<head><style>
*{margin:0px; padding:0px;}
.wrap {
background-color:blue;
text-align:center;
width:300px;
height:300px;
}
.wrap2 {
display:inline-block;
width:0px;
height:100%;
vertical-align:middle;
}
.test {
display:inline-block;
background-color:red;
}
</style>
</head>
<body>
<div class="wrap">
<b class="wrap2"></b>
<div class="test">
hha
</div>
</div>
</body>
</html>
结果如下:
3.借助transform:translate的方法,因为这个是按照自己本身做的偏移
代码:
<!DOCTYPE html>
<html>
<head><style>
*{margin:0px; padding:0px;}
.test {position: absolute; left:50%; top:50%; -webkit-transform:translate(-50%,-50%); transform:translate(-50%,-50%);background-color:blue;}
</style>
</head>
<body>
<div class="test">
<div style='width:300px;height:300px;'>hah</div>
//或者<div >hah</div>
</div>
</body>
</html>
但是上文在IE环境不支持
4.按照css3的新属性 box box-align:垂直居中box-center:水平居中
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body >
<div style="width:300px; height: 300px; background-color: #ccc;
line-height: 300px; text-align: center;">
<div>sss</div>
</div>
<div style="width:300px; height: 300px; background-color: #aaa;
display:-webkit-box;-webkit-box-pack: center;
; -webkit-box-align:center">
<div style='background-color:blue;width:20px;height:20px;'>sss</div>
</div>
</body>
</html>