情况一:盒子的高度和宽度是已知或者未知。
思路:用定位来解决
- 父元素相对定位;
- 子元素绝对定位;
- left: 50%; top: 50%;
- margin-left: 负的一半宽度; margin-top: 负的一半高度。或者用位移来做。
上代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<style>
.father {
position: relative;
width: 1000px;
height: 1000px;
background-color: aquamarine;
}
.son {
position: absolute;
width: 200px;
height: 400px;
background-color: pink;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
</style>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
</html>
ps:其中son盒子的style中的 transform: translate(-50%, -50%);可以换成margin-top:-200px
margin-left:-100px;其原理是向右向下移动父亲盒子的一半,同时向上向左移动自身的一半。这样
盒子就水平垂直居中了
上效果:
情况二:盒子的宽度和高度已知或者未知的
思路:用定位来解决
- 父元素相对定位;
- 子元素绝对定位;
- top: 0; right: 0; bottom: 0; left: 0;
- margin: auto;
上代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<style>
.father {
position: relative;
width: 1000px;
height: 1000px;
background-color: rgb(14, 55, 42);
}
.son {
position: absolute;
width: 200px;
height: 200px;
background-color: rgb(199, 101, 117);
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
}
</style>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
</html>
上效果:
情况三:盒子的宽度和高度已知或者未知的:
思路:flex 布局。(万能的flex布局,希望大家一定要记住,很好用奥。)
- 在父级元素中采用flex布局:display: flex; justify-content: center; align-items: center;
上代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<style>
.father {
display: flex;
justify-content: center;
align-items: center;
width: 1000px;
height: 1000px;
background-color: rgb(115, 192, 48);
}
.son {
width: 200px;
height: 200px;
background-color: rgb(90, 136, 157);
}
</style>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
</html>
上效果: