想必大家都知道,盒子居中不论在项目中还是在面试题中都是常见的对吧!今天我主要分享四种方法,希望对各位同学有一定的帮助。
场景:
假如这里有一个父盒子(parent),子盒子(child),我们需要得到的结果是让子盒子相对父盒子居中,也就是说子盒子在父盒子中居于中间的位置。
,以便于大家更好的理解。
盒子居中一般有两种类型,
1.宽度和高度已经确定的。
2.宽度和高度未确定的。
有四种解决方案:
1.宽度和高度已经知道的
2.宽度和高度不知道的
3.flex布局
4.css3的方法
1.子盒子的宽度和高度已经知道的
思路:
给父盒子相对定位,给子盒子绝对定位,top:50%,left:50%;
这时我么发现子盒子相对父盒子并没有居中,这是因为子盒子本身也是有宽度的,因此我们需要减去子盒子自身的一半。即:margin-left: 负的子盒子宽度的一半;margin-top: 负的子盒子高度的一半;
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>盒子模型</title>
<style>
*{
margin: 0;
padding: 0;
}
.parent{
width: 300px;
height: 300px;
background: #f99;
position: relative;
}
.child {
background: #9ff;
}
/*宽度已经确定的*/
.box-center {
width: 100px;
height: 100px;
position: absolute;
top: 50%;
left: 50%;
margin-left: -50px;
margin-top: -50px;
}
</style>
</head>
<body>
<div class="parent">
父盒子
<div class="child box-center">
我是子盒子
</div>
</div>
</body>
</html>
2.子盒子的宽度和高度是未知的(这里需要注意的是,子盒子的宽度和高度其实是有的,只是在不知道的情况下采取这种方式居中)
思考:如果子盒子没有宽度和高度会出现什么情况呢?
思路:给父盒子相对定位,给子盒子绝对定位,让子盒子的top、left、right、bottom都为0,然后来个margin: auto;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>盒子模型</title>
<style>
*{
margin: 0;
padding: 0;
}
.parent{
width: 300px;
height: 300px;
background: #f99;
position: relative;
}
.child {
background: #9ff;
}
/*宽度和高度未确定的*/
/*意思就是说宽度和高度本身是存在的只是自己未知*/
.no-center {
width: 100px;
height: 100px;
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
}
</style>
</head>
<body>
<div class="parent">
父盒子
<div class="child no-center">
我是子盒子
</div>
</div>
</body>
</html>
3.flex布局
思路:利用flex进行居中,不管子盒子的宽度和高度是否知道,只需要给父盒子加一个center类(类名可以随意)即可。这里需要注意是给父盒子加这个center类,子盒子才能居中。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>盒子模型</title>
<style>
*{
margin: 0;
padding: 0;
}
.parent{
width: 300px;
height: 300px;
background: #f99;
position: relative;
}
.child {
background: #9ff;
}
/*flex布局*/
.center {
display: flex;
justify-content: center;
align-items: center;
}
</style>
</head>
<body>
<div class="parent">
父盒子
<div class="child transform-center">
我是子盒子
</div>
</div>
</body>
</html>
4.css3的方法(平移)
思路:利用css3中的translate可以实现盒子居中
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>盒子模型</title>
<style>
*{
margin: 0;
padding: 0;
}
.parent{
width: 300px;
height: 300px;
background: #f99;
position: relative;
}
.child {
background: #9ff;
}
.transform-center {
width: 100px;
height: 100px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
</style>
</head>
<body>
<div class="parent">
父盒子
<div class="child transform-center">
我是子盒子
</div>
</div>
</body>
</html>
其实这四种方法中,比较常用的是第一种和第三种。应该还有其他的方法,欢迎大家补充。