块级盒子的绝对居中
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>块级盒子绝对居中的方法</title>
<style>
.wrapper{
width: 200px;
height: 300px;
margin: 100px auto;
border: 1px solid #f5f5f5;
box-sizing: border-box;
}
.box{
width: 100px;
height: 100px;
border: 1px solid red;
box-sizing: border-box;
}
</style>
</head>
<body>
<div class='wrapper'>
<div class='box'>
这是元素1
</div>
</div>
</body>
</html>
在不知道父元素和子元素宽高的情况下
第一种使用弹性和模型(flex)
父元素设置display: flex;成为容器盒子,然后设置主轴和交叉轴上对齐方式
即:justify-content:center; align-item: center;
<style>
.wrapper{
display: flex;
width: 200px;
height: 300px;
margin: 100px auto;
justify-content: center;
align-items: center;
background-color: rgba(0,0,0,.3);
}
.box{
width: 100px;
height: 100px;
border: 1px solid red;
box-sizing: border-box;
}
</style>
第二种使用定位
父元素设置相对定位,子元素设置绝对定位
子元素设置top,bottom,left,right设置值一样,然后设置margin:auto;
<style>
.wrapper{
position: relative;
width: 200px;
height: 300px;
margin: 100px auto;
background-color: rgba(0,0,0,.3);
}
.box{
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
width: 100px;
height: 100px;
margin: auto;
border: 1px solid red;
box-sizing: border-box;
}
</style>
在知道父元素和子元素宽高的情况下
第一种使用父元素padding值
根据子元素的宽高设置父元素的padding值
当然为了使父元素盒子不变大,父元素需要设置box-sizing: border-box;
<style>
.wrapper{
width: 200px;
height: 300px;
margin: 100px auto;
padding: 100px 50px;
background-color: rgba(0,0,0,.3);
}
.box{
width: 100px;
height: 100px;
border: 1px solid #ccc;
box-sizing: border-box;
}
</style>
第二种使用子元素margin值
根据父元素的宽高设置子元素的margin值
还要确保父元素和子元素不会发生外边距合并的情况
<style>
.wrapper{
width: 200px;
height: 300px;
margin: 100px auto;
border: 1px solid #ccc;
box-sizing: border-box;
background-color: rgba(0,0,0,.3);
}
.box{
width: 100px;
height: 100px;
margin: 100px auto;
border: 1px solid red;
box-sizing: border-box;
}
</style>
不知道父级宽高,知道子元素宽高
不知道父元素宽高,知道子元素宽高
还是需要借助定位
子元素定位top,left值都设成50%,然后margin-top,margin-left都各设置高和宽的一般的负值
<style>
.wrapper{
position: relative;
width: 200px;
height: 300px;
margin: 100px auto;
background-color: rgba(0,0,0,.3);
}
.box{
position: absolute;
top: 50%;
left: 50%;
width: 100px;
height: 100px;
margin-top: -50px;
margin-left: -50px;
border: 1px solid #666;
box-sizing: border-box;
}
</style>
暂时只想出来这么多,如果您还有别的方法,请告知,在下面留言,谢谢
365

被折叠的 条评论
为什么被折叠?



