css 垂直居中常用的方法
如何将一个未知高度的元素垂直居中,通常有两种常用的方法:
//html <div class="parent"> <div class="child">center</div> </div>
1、用绝对定位和translate
.parent{ height: 300px; width: 300px; position: relative; background-color: bisque; } .child{ position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%); padding: 30px; background-color: cornflowerblue; }
2、基于 Flexbox
的解决方案
这是毋庸置疑的最佳解决方案,因为 Flexbox 是专门针对这类需求所设计的,只是一些老的浏览器版本兼容性可能不是很好,具体可以查看caniuse,现代浏览器一般没问题。
.parent{ height: 300px; width: 300px; background-color: bisque; display: flex; justify-content: center; align-items: center; } .child{ padding: 30px; background-color: cornflowerblue; }
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
码云笔记 » css 垂直居中常用的方法
码云笔记 » css 垂直居中常用的方法