一个200*200的div在不同分辨率屏幕上下左右居中可以用以下几种方式:
(1)负margin-left和margin-top
负margin-left和margin-top实现居中时,margin-left必须知道自身的宽高。
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
#testdiv{
position: absolute;
width: 200px;
height: 200px;
top: 50%; /* 距顶部50%*/
left: 50%; /* 距左边50%*/
margin-left:-100px; /*margin-left为width一半的负值*/
margin-top:-100px; /*margin-top为height一半的负值*/
z-index:1000;
background-color: red;
}
</style>
</head>
<body>
<div id="testdiv"></div>
</body>
</html>
效果:
(2)translate
translate()函数是css3的新特性,在不知道自身宽高的情况下,可以利用它来进行水平垂直居中。
当使用:top: 50%;left: 50%;, 是以左上角为原点,故不处于中心位置
translate(-50%,-50%) 作用是,往上(x轴),左(y轴)移动自身长宽的 50%,以使其居于中心位置。
translate可以在不知道宽高的情况下进行居中,tranlate()函数中的百分比是相对于自身宽高的百分比,所以能进行居中
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
#testdiv{
position: absolute;
width: 200px;
height: 200px;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
-ms-transform:rotate(-50%,-50%); /* Internet Explorer */
-moz-transform:rotate(-50%,-50%); /* Firefox */
-webkit-transform:rotate(-50%,-50%); /* Safari 和 Chrome */
-o-transform:rotate(-50%,-50%); /* Opera */
background-color: yellow;
}
</style>
</head>
<body>
<div id="testdiv"></div>
</body>
</html>
(3)left:0;right:0;margin:auto 可以使元素水平居中; top:0;bottom:0;margin:auto 可以使元素垂直居中。所以,设置四个值都是0;margin:auto;后,这个元素就在正中间了。
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
#testdiv{
position: absolute;
width: 200px;
height: 200px;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
background-color: pink;
}
</style>
</head>
<body>
<div id="testdiv"></div>
</body>
</html>
效果: