如何用CSS替代JavaScript实现图片按钮的正方形比例保持?
CSS实现Flex布局中图片按钮的正方形比例(替代JavaScript方案)
我用Flex布局在容器中排列一系列按钮,普通按钮的宽高由内边距和文本决定,图片按钮设置了height:100%。目前只能通过JavaScript将其宽度设为高度来维持正方形比例,尝试使用aspect-ratio属性未成功,求纯CSS实现方案。
原示例代码
JavaScript代码
makeSquare(".image button"); window.addEventListener("resize", () => { makeSquare(".image button"); }); function makeSquare(selector) { const buttons = document.querySelectorAll(selector); buttons.forEach((button) => { button.style.width = `${button.offsetHeight}px`; }); }
CSS代码
.wrapper { display: flex; align-items: stretch; } .regular button { padding: 20px 40px; background-color: #aaaaaa; } .image button { height: 100%; background-image: url("https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcT7vnGsgBgV8QW50dp-wZ4GoCNWu4egKYuxAw&s"); background-repeat: no-repeat; background-position: center center; background-size: cover; }
HTML代码
<div class="wrapper"> <div class="regular"> <button>RegA</button> </div> <div class="image"> <button></button> </div> <div class="regular"> <button>RegB</button> </div> </div>
纯CSS解决方案
方案一:利用aspect-ratio属性(现代浏览器)
直接给图片按钮的父容器(.image)设置aspect-ratio: 1/1,让这个flex项保持正方形,再让按钮占满整个容器即可:
.wrapper { display: flex; align-items: stretch; } .regular button { padding: 20px 40px; background-color: #aaaaaa; } .image { aspect-ratio: 1/1; /* 强制flex项为正方形,宽度自动匹配高度 */ } .image button { width: 100%; height: 100%; background-image: url("https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcT7vnGsgBgV8QW50dp-wZ4GoCNWu4egKYuxAw&s"); background-repeat: no-repeat; background-position: center center; background-size: cover; }
原理:.wrapper的align-items: stretch会让所有flex项高度统一,.image设置aspect-ratio:1/1后,其宽度会自动等于自身高度(由其他flex项的高度决定),按钮设置宽高100%即可填满这个正方形容器。
方案二:padding-top百分比技巧(兼容旧浏览器)
如果需要兼容不支持aspect-ratio的浏览器,可利用padding-top百分比基于父元素宽度的特性,配合绝对定位实现:
.wrapper { display: flex; align-items: stretch; } .regular button { padding: 20px 40px; background-color: #aaaaaa; } .image { position: relative; width: 0; flex-grow: 1; /* 让宽度自适应高度 */ } .image::before { content: ''; display: block; padding-top: 100%; /* 100% 对应1:1的正方形比例 */ } .image button { position: absolute; top: 0; left: 0; width: 100%; height: 100%; background-image: url("https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcT7vnGsgBgV8QW50dp-wZ4GoCNWu4egKYuxAw&s"); background-repeat: no-repeat; background-position: center center; background-size: cover; }
原理:.image设置width:0和flex-grow:1,让其宽度由内部的padding-top撑开;padding-top:100%会使元素高度等于宽度,形成正方形;最后通过绝对定位让按钮占满整个容器。
内容的提问来源于stack exchange,提问作者TheLovelySausage
相关产品推荐
相关产品推荐

