基礎知識常備1:盒子垂直水平居中問題
實現效果:
html:公用部分
<!-- 父元素 -->
<div class="f">
<!-- 子元素 -->
<div class="s">
</div>
</div>
方法1:(利用定位方式子絕父相1)
.f {
/* 子絕父相 */
position: relative;
height: 500px;
width: 500px;
background-color: pink;
margin: 100px auto;
}
.s {
/* 子絕父相 */
position: absolute;
height: 200px;
width: 200px;
background-color: red;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
}
此種方法你要掌握,定位的相關特性哦,這裏主要用到了絕對定位以及相對定位,設置上下左右屬性爲0,margin屬性爲auto 便可實現居中效果
方法2:(利用定位方式子絕父相2)
.f {
/* 子絕父相 */
position: relative;
height: 500px;
width: 500px;
background-color: pink;
margin: 100px auto;
}
.s {
/* 子絕父相 */
position: absolute;
height: 200px;
width: 200px;
background-color: red;
left: 50%;
top: 50%;
margin-top: -100px;
margin-left: -100px;
}
此種方法也是主要用到“子絕父相”的特性,區別於第一種“子”的巧妙利用負自身寬高的一半進行居中
方法3:(利用定位方式子絕父相3-未指定盒子盒子的寬度和高度)
針對於上面的第二種的方法,有的小夥伴就會想,還要算自身的高度,很麻煩,我我只能算10以內的加減法,沒關係我們可以利用位移來解決此計算問題,快來試試吧!
.f {
/* 子絕父相 */
position: relative;
height: 500px;
width: 500px;
background-color: pink;
margin: 100px auto;
}
.s {
position: absolute;
//未指定盒子盒子的寬度和高度
//解釋一下:並不是不設置盒子的寬高,而是咱們提前不知道盒子的寬高
height: 200px;
width: 200px;
background-color: red;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
方法4:(利用flex佈局(彈性佈局))
.f {
display: flex;
justify-content: center;
align-items: center;
height: 500px;
width: 500px;
background-color: pink;
margin: 100px auto;
}
.s {
height: 200px;
width: 200px;
background-color: red;
}
此種方法也是比較方便的一種,巧妙利用彈性盒子, justify-content: center;主軸上居中顯現,align-items: center;側軸上居中顯示,這樣就能形成一個垂直水平居中的效果。
未完待續,有更好的方法我會及時更新的,歡迎大家前來評論