盒子居中的方法大全
<div class="father">
<div class="children">
</div>
</div>
1.绝对定位法⭐
父元素和子元素都有宽度,并且父元是相对定位 position: relative,子元素可以设置成绝对定位 position: absolute。设置 top left bottom right 的距离为 0 后,直接 margin:auto 。
附:如果只想垂直居中的,只需要设置 top 和 bottom 。
.father {
border: 1px solid #000000;
/**/
width: 200px;
height: 200px;
position: relative;
}
.children {
width: 100px;
height: 100px;
background: #9696ff;
/**/
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
2.负margin居中
这种方法太笨重了,需要知道子元素的固定宽高。
通过 left:百分比,然后使用 margin 自身宽、高度的一半。
.father {
width: 200px;
height: 200px;
border: 1px solid #000000;
/**/
position: relative;
}
.children {
width: 100px;
height: 100px;
position: absolute;
background: #9696ff;
/**/
top: 50%;
left: 50%;
margin-top: -50px; /* 子元素的宽一半 */
margin-left: -50px; /* 子元素的高一半 */
}
3.正margin居中
反正我觉得 margin 的东西都挺奇怪的。
这种方式倒是不需要使用 left: 百分比 了。但是就是传统意义上说的,写“死”了。正 margin 完全是用父元素与子元素的距离算出来的。
.father {
width: 200px;
height: 200px;
border: 1px solid #000000;
/**/
}
.children {
width: 100px;
height: 100px;
background: #9696ff;
/**/
margin-left: 50px;
margin-top: 50px;
/* 其实这样也可以 margin: 50px 50px; */
}
4.flex居中⭐
我可以说,这是一种最轻松的居中方式了。只需要设置父元素的样式,子元素管你啥样。不过这样的话,子元素只能有一个,不然会抢占居中的位置。
.father {
width: 200px;
height: 200px;
border: 1px solid #000000;
/**/
display: flex;
justify-content: center;
align-items: center;
}
.children {
width: 100px;
height: 100px;
background: #9696ff;
/**/
}
5.transform居中⭐
这种居中方式和margin负居中很像。只不过是IE9一下不支持。不过这年头了谁还用这玩意啊。
一样的方式,先距离父元素 50%,在以自身的框和高 -50% 来对齐居中。
.father {
width: 200px;
height: 200px;
border: 1px solid #000000;
/**/
}
.children {
width: 100px;
height: 100px;
background: #9696ff;
/**/
position: relative;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
6.table-cell居中
它就是把父元素当成一个表格,然后使用它的垂直居中,接着 margin: 0 auto 看运气,非常不常用的一种方式。
.father {
width: 200px;
height: 200px;
border: 1px solid #000000;
/**/
display: table-cell;
vertical-align: middle;
}
.children {
width: 100px;
height: 100px;
background: #9696ff;
/**/
margin: 0 auto;
}
7.不确定宽高居中⭐
这种较为灵活。只需要保证 left 和 right 的百分数一样就可以实现水平居中,保证 top 和 bottom 的百分数一样就可以实现垂直居中。
像是当成了 padding 来用。
.father {
width: 200px;
height: 200px;
border: 1px solid #000000;
/**/
position: relative;
}
.children {
background: #9696ff;
/**/
position: absolute;
left: 10%;
right: 10%;
top: 10%;
bottom: 10%;
}