前端面试CSS系列——DIV垂直居中水平居中
时间:2023-03-30 18:47:26
CSS
绝对定位。parent{position:relative;}//首先输入.child{position:absolute;顶部:50%;左:50%;transform:translate(-50%,-50%);}//第二种(要求固定宽高).child{position:absolute;宽度:100px;高度:100px;顶部:50%;左:50%;左边距:-50px;margin-top:-50px;}//第三种(要求固定宽高).child{position:absolute;宽度:100px;高度:100px;左:0;顶部:0;底部:0;右:0;margin:auto;}//四中(定宽高+transform).child{position:absolute;宽度:100px;高度:100px;左:50%;顶部:50%;背景:黄色;transform:translate(-50px,-50px);}flexlayout.parent{宽度:500px;;显示:弹性;对齐项目:居中;justify-content:center;}//子元素可以有固定的宽度和高度。parent.child{宽度:100px;高度:100px;background:yellow;}//子元素不设置width和height.parent.child{background:yellow;}table-cell.parent{width:500px;高度:500px;显示:表格单元格;文本对齐:居中;垂直对齐:中间;背景:粉色;}.parent.child{显示:内联表;/*//这个方法也可以显示:inline-block;显示:内联;*/宽度:100px;高度:100px;背景:黄色;}Grid.parent{宽度:500px;高度:500px;;证明自我:中心;宽度:100px;高度:100px;background:yellow;}Demo总结了两种情况让div垂直居中和水平居中。首先是元素没有固定的宽度和高度。使用绝对定位有3种方式添加transformoffset使用flex布局,设置align-items:center;证明内容:居中;使用网格布局,设置align-self:center;自我辩护:中心;如果元素有固定的宽高,可以使用:绝对定位+transformoffset绝对定位+negativemarginvalueabsolutepositioning+margin:autodoesnotfixedwidthandheight三种方式参考前端进阶