一个盒子垂直水平居中的几种方法总结
效果展示:
HTML代码:
<div id="container">
<div id="box"></div>
</div>
css基本样式:
#container {
width: 100%;
height: 600px;
border: 1px solid black;
}
#box {
width: 100px;
height: 100px;
background: red;
}
方法一:定位 absolute + 负margin
#container {
width: 100%;
height: 600px;
border: 1px solid black;
position: relative;
}
#box {
width: 100px;
height: 100px;
background: red;
position:absolute;
top: 50%;
left: 50%;
margin-left: -50px; /* 左偏移量取其元素宽度的一半的负值 */
margin-top: -50px; /* 上偏移量取其元素高度的一半的负值 */
}
解释:为父元素设置了相对定位之后,子元素的绝对定位就是相对于父元素盒子的左上顶点,所以定位之后我们需要回退盒子一半的距离。
方法二:定位absolute + margin auto
#container {
width: 100%;
height: 600px;
border: 1px solid black;
position: relative;
}
#box {
width: 100px;
height: 100px;
background: red;
position:absolute;
top:0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
方法三:table-cell
#container{
width:600px;
height: 600px;
border: 1px solid black;
display:table-cell;
vertical-align: middle;
text-align: center;
}
#box{
width: 100px;
height: 100px;
background: red;
display: inline-block;
}
注意:不能对display:table-cell的div使用百分比设置宽度和高度;
方法四:弹性盒子display: flex
#container{
width:600px;
height: 600px;
border: 1px solid black;
display: flex;
justify-content: center;
align-items: center;
}
#box{
width: 100px;
height: 100px;
background: red;
}
方法五:利用transform
#container{
width:600px;
height: 600px;
border: 1px solid black;
position: relative;
}
#box{
width: 100px;
height: 100px;
background: red;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
方法六:利用calc计算
扫描二维码关注公众号,回复:
12832828 查看本文章
#container{
width:600px;
height: 600px;
border: 1px solid black;
position: relative;
}
#box{
width: 100px;
height: 100px;
background: red;
position: absolute;
top: calc(250px);
left: calc(100%-100px);
}
注意: top = 父元素的高度-子元素的高度, left = 父元素的宽度-子元素的宽度 ;
方法七:网格布局
#container{
width:600px;
height: 600px;
border: 1px solid black;
display:grid;
}
#box{
width: 100px;
height: 100px;
background: red;
align-self: center;
justify-self: center;
}
关于网格布局的更多知识详解可参考阮一峰老师的讲解,链接:http://www.ruanyifeng.com/blog/2019/03/grid-layout-tutorial.html
方法八:计算父盒子与子盒子的空间距离
#container{
width:600px;
height: 600px;
border: 1px solid black;
}
#box{
width: 100px;
height: 100px;
background: red;
margin-left:250px;
margin-top: 250px;
}
计算方法:父盒子高度或者宽度的一半减去子盒子高度或者宽的的一半。这个要根据自己设置的实际宽高进行计算;
以上就是我关于一个盒子在垂直水平位置居中的几种方法的一些见解和总结,关于文本的居中方法在这里就不做赘述,感兴趣的可以参考我的另一篇博客,如有不足,欢迎指正。
单行文本+多行文本垂直水平居中的设置方法:https://blog.csdn.net/qq_43692768/article/details/109412944