CSS垂直居中的四种实现方案详解
作者:麦兜 更新时间:2025-09-03 13:04:01 阅读 189
「4种方案」搞定CSS水平垂直居中
关注我的头条号,分享更多的技术学习文章,我自己是一名从事了多年开发的web前端老程序员,目前辞职在做自己的web前端私人定制课程,今年我花了一个月整理了一份最适合2020年学习的web前端学习干货,各种框架都有整理,送给每一位前端小伙伴,想要获取的可以关注我的头条号并在后台私信我:前端,即可免费获取。
方案一:position绝对定位+margin负值
适用:子元素有宽高尺寸方法:父元素相对定位,子元素绝对定位,left和top定位到父元素50%,再用margin向左和向上移动子元素尺寸的一半。.wrapper{ background: #1890ff; height: 400px; width:400px; position: relative; } .content{ background: #FFB90F; width: 200px; height:200px; position: absolute; left: 50%; top:50%; margin:-100px 0 0 -100px; } 复制代码效果:
方案二:position绝对定位+transform调整位置
适用:子元素未知宽高(当然知道也可以啦!)方法:此方法与方案一是一个道理,将margin换为transform:translate(-50%,-50%)。.wrapper{ background: #1890ff; height: 400px; width:400px; position: relative; } .content{ background: #FFB90F; /*width: 200px;*/ /*height:200px;*/ position: absolute; left: 50%; top:50%; transform: translate(-50%,-50%); } 复制代码效果:
方案三:position绝对定位+margin:auto
适用:子元素有宽高尺寸方法:父元素相对定位,子元素绝对定位,left、right、top、bottom设置为0,再用margin:auto。.wrapper{ background: #1890ff; height: 400px; width:400px; position: relative; } .content{ background: #FFB90F; width: 200px; height:200px; position: absolute; left: 0; right:0; top:0; bottom:0; margin:auto; } 复制代码效果:与方案一相同。
方案四:flex弹性盒
适用:子元素未知宽高(当然知道也可以啦!)方法:父元素设置为弹性盒,justify-content和align-items都设置为center居中。.wrapper{ background: #1890ff; height: 400px; width:400px; display: flex; justify-content: center;/*主轴方向居中*/ align-items:center;/*侧轴方向居中*/ } .content{ background: #FFB90F; /*width: 200px;*/ /*height:200px;*/ } 复制代码效果:与方案二相同。
效果:与方案二相同。
链接:https://juejin.cn/post/6915756476208414727
作者:变态的小水瓶
出处:掘金
声明:本文由"麦兜"发布,不代表"破站"立场,转载联系作者并注明出处:https://www.848586.cn/244493.html
