HTML
<form action="">
<div id="div1">
<div id="div2">
</div>
</div>
</form>
a.第一种,justify-content(横轴居中),align-items(元素整体居中)
#div1 {
border: 1px solid;
width: 100px;
height: 100px;
display: flex;
justify-content: center;
align-items: center;
}
#div2 {
border: 1px solid;
width: 30px;
height: 30px;
}
b.第二种,justify-content(横轴居中),align-self(小 div 自身纵轴居中)
#div1 {
border: 1px solid;
width: 100px;
height: 100px;
display: flex;
justify-content: center;
}
#div2 {
border: 1px solid;
width: 30px;
height: 30px;
align-self: center;
}
c.第三种,定位法,父元素相对定位(relative),子元素绝对定位(absolute),div2 width = (div1 width - div2 width) / 2,height 同理!
#div1 {
border: 1px solid;
width: 100px;
height: 100px;
position: relative;
}
#div2 {
border: 1px solid;
width: 30px;
height: 30px;
position: absolute;
left: 35px;
top: 35px;
}
d.第四种,定位法,未知 div 宽高的时候
#div1 {
border: 1px solid;
width: 100px;
height: 100px;
position: relative;
}
#div2 {
border: 1px solid;
width: 30px;
height: 30px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
注:translate 可以理解为在 x,y 轴上进行移动,想象屏幕中间有一个十字,div2 紧贴第四象限,
然后利用 transform 属性,将其往左平移 div 自身长度的50%,往上平移 div 自身长度的50%,实现居中。
e.脱离文档流,margin 居中
#div1 {
border: 1px solid;
width: 100px;
height: 100px;
position: relative;
}
#div2 {
border: 1px solid;
width: 30px;
height: 30px;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
设置
position
属性,上下左右均为0
(脱离文档流,并使其填充父级所有可用空间),然后给
div
设置宽高,防止其占用父级所有可用空间,最后再设置
margin:auto
(等同于margin-top:0;margin-bottom:0
)使浏览器重新计算外边距,以达到垂直水平居中效果。