html中盒⼦的居中⽅式(五种)
年轻就应该横冲直撞,毫不畏惧,有梦想,有活⼒。
1.利⽤margin与定位
/*⽗级*/
position:relative;
/*⼦级*/
position:absolute;
top:0;
left:0;
bottom:0;
right:0;
margin:auto;
详解:
设置margin⾃动适应,然后设置定位的上下左右都为0,就如四边均衡受⼒从⽽实现盒⼦的居中;
2.利⽤table-cell
/*⽗级*/
display:table-cell;
text-align:center;
vertical-align: middle;
/*⼦级*/
display:inline-block
详解:
将⽗盒⼦设置为table-cell(能够使元素呈单元格的样式显⽰),并设置text-align: center(使内容⽔平居中);vertical-align:middle(使内容垂直居中);。⼦盒⼦设置为inline-block可以使其内容变为⽂本格式,也可设置宽⾼;此⽅法⽗级需设置指定⾼度和宽度,负责⽆效
3.利⽤flex弹性盒⼦
/*⽗级*/
display: flex;
justify-content: center;
align-items: center;
详解:
使⽤弹性盒⼦的时候需要给⽗级设置display:flex;
在⽗元素上设置⽔平justify-content:center;与垂直align-items:center;⽅向上的排列⽅式即可
4.利⽤定位+位移
/*⽗级*/
position:ablative;
/*⼦级*/
position:absolute;
left:50%;
top:50%;
transform:translate(-50%,-50%)
详解:
利⽤定位将⼦级进⾏向右下⽅向进⾏"驱逐",使⼦级的左上⾓那⼀点相对于⽗级居中,然后使⽤transform(相对于⾃⾝的位移)进⾏反向位移
5.利⽤定位+margin(宽⾼的⼀半)
/*⽗级*/
position:ralatiive;
/*⼦级*/
height:50px;
width:50px;
position:absolute;
top:50%;
left:50%;
margin-top:-25px;
margin-left:-25px;html怎么让所有内容居中
详解:
利⽤定位将盒⼦挤向右下⽅,再利⽤margin进⾏反向回推。(原理和定位+位移的⽅法如同⼀辙)