当前位置: 首页 > Web前端 > CSS

css实现水平和垂直居中的四种方法

时间:2023-03-30 15:27:45 CSS

HTML结构:

1、已知元素的宽高:.item{位置:绝对;顶部:50%;左:50%;边距顶部:-75px;/*将margin-left/margin-top设置为其高度的一半*/margin-left:-75px;}.item{position:absolute;保证金:自动;左:0;顶部:0;右:0;bottom:0;}/*该方法可以实现自适应*/2.未知元素高度和宽度:.item{position:absolute;顶部:50%;左:50%;转换:翻译(-50%,-50%);/*使用css3的transform实现*/}.parent{display:flex;证明内容:居中;对齐-items:center;背景:#AAA;高度:300px;/*注意这里需要设置高度才能看到垂直居中的效果*/}