对于position:fixed的元素,我们可以使用left,top配合margin-left,margin-top实现。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title></title>
</head>
<body>
<div class="mydiv">
</div>
<style type="text/css">
*{
padding: 0;
margin: 0;
}
.mydiv{
position:fixed;
width: 300px;
height: 200px;
top: 50%;
left: 50%;
margin-top: -150px;
margin-left: -100px;
background-color: red;
}
</style>
</body>
</html>
这里mydiv的宽高都是固定的,所以我们可以用这种方式实现。但是如果它的宽高不固定,我们就得用transform中的translate实现了。代码如下:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title></title>
</head>
<body>
<div class="mydiv">
</div>
<style type="text/css">
*{
padding: 0;
margin: 0;
}
.mydiv{
position:fixed;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
background-color: red;
}
</style>
</body>
</html>