如何在不使用aspect-ratio的固定宽高比div内居中显示文本?
实现方案
你原来的padding-top实现固定宽高比的逻辑是完全正确的,问题只在于没有补充垂直居中的规则,以下两种方案兼容性都覆盖了包括旧版Safari在内的所有主流浏览器,无需使用aspect-ratio属性:
方案1:flex布局(兼容IE11及以上)
在铺满外层容器的绝对定位元素上开启flex居中,适合需要对内部多元素排版的场景:
.aspect-ratio-div{ background-color: #f2f2f7; position: relative; width: 100%; /* 3:1宽高比 = 高度/宽度 = 1/3 ≈ 33.33% */ padding-top: 33.33%; } .text-wrapper{ position: absolute; top: 0; left: 0; bottom: 0; right: 0; /* 新增以下3行实现垂直+水平居中 */ display: flex; align-items: center; justify-content: center; font-size: 20px; color: #333; }
<div class="aspect-ratio-div"> <div class="text-wrapper"> <label>This is some centered text</label> </div> </div>
方案2:transform位移(兼容IE9及以上)
直接将文本定位到容器中心,代码更简洁,适合仅居中单个文本元素的场景:
.aspect-ratio-div{ background-color: #f2f2f7; position: relative; width: 100%; padding-top: 33.33%; } .text-wrapper{ position: absolute; /* 先定位到容器50%的位置,再用translate往回偏移自身宽高的一半 */ top: 50%; left: 50%; transform: translate(-50%, -50%); font-size: 20px; color: #333; }
<div class="aspect-ratio-div"> <label class="text-wrapper">This is some centered text</label> </div>
内容的提问来源于stack exchange,提问作者Aadhit Shanmugam
相关产品推荐
相关产品推荐

