<!DOCTYPE html>
<html>
<head>
<title>my-test</title>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
.content {
padding: 20px;
background: orange;
color: #fff;
position: absolute;
top: 50%;
left: 50%;
border-radius: 5px;
-webkit-transform: translate(-50%, -50%);
-moz-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}
</style>
</head>
<body>
<div class="content">
我不知道我的高度和宽度是多少。
</div>
</body>
</html>
二、盒子有固定的宽和高
方案1、margin 负间距
1.必需知道该div的宽度和高度,
2.然后设置位置为绝对位置,
3.距离页面窗口左边框和上边框的距离设置为50%,这个50%就是指盒子左上角顶点距离页面左、上边界的50%,
4.最后将该div分别左移和上移,使整个盒子居中,左移和上移的大小就是该DIV(包括border和padding)宽度和高度的一半。
<!DOCTYPE html>
<html>
<head>
<title>my-test</title>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
.content {
position: absolute;
width: 200px;
height: 200px;
border: 2px solid red;
background-color: yellow;
left:50%;
top:50%;
margin-left:-102px;
margin-top:-102px;
}
</style>
</head>
<body>
<div class="content">
我有固定的宽度和高度。
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>my-test</title>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
.content {
position: absolute;
width: 200px;
height: 200px;
border: 2px solid red;
background-color: yellow;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
}
</style>
</head>
<body>
<div class="content">
我有固定的宽度和高度。
</div>
</body>
</html>
原文链接:https://blog.csdn.net/qq_34200964/article/details/81711989
相关文章