块级元素水平垂直居中方法总结

it2023-04-12  66

.father{

width:M px;

height:N px;

}

.child{

width:m px;

height: n px;

}

1.绝对定位与边距负值

直接在子元素中margin-top、margin-bottom定位,会出现margin塌陷,就是会带动父元素一起移动

正确做法是:

父元素

.father{

positon:relative;

width:M px;

height:N px;

}

子元素

.child{

positon:absolute;

top:50%;

left:50%;

width:m px;

height: n px;

margin:-n/2 px 0 0 -m/2px;/*上:负子元素高度的一半,右0 ,下0,左:负子元素宽度的一半*/

}

 

2.绝对定位UI外边距自动操作

.father{

width:M px;

height:N px;

padding:150px;父元素向外分别扩展150px

box-sizing:border-box;/使父元素盒子向内部绘制150px

}

子元素不变

 

3.内边距操作

.father{

position:relative;

width:M px;

height:N px;

}

.child{

position:absuolute;

top:0;

left:0;

right:0;

bottom:0;

margin:auto;

width:m px;

height: n px;

}

 

4.浮动盒子

占位

.father{

width:M px;

height:N px;

}

.floater{

float:left;

width:100%;

height:50%;

margin-bottom:-n/2 px;/*使子元素垂直居中*/

}

.child{

clear: both;/清除浮动/

margin:0 auto;/*水平居中*/

width:m px;

height: n px;

}

5.flex布局

.father{

display:flex;/*弹性盒子,涉及兼容性,PC端使用较少*/

justify-content:center;

align-items:center;/*垂直和水平都居中*/

width:M px;

height:N px;

}

.child{

width:m px;

height: n px;

}

最新回复(0)