CSS如何实现基于图片自身尺寸而非父容器大小调整图片尺寸
解决方案
你可以通过以下两种常用方案实现基于图片自身尺寸的百分比缩放:
方案1:使用transform: scale()(最简单直接)
scale()的缩放比例默认基于元素自身的原始尺寸计算,刚好匹配你的需求,不需要修改现有DOM结构,只需要调整CSS即可:
.small-logos img { /* 数值0.5对应原尺寸的50%,按需调整即可 */ transform: scale(0.5); /* 可选:如果需要从左上角开始缩放,避免默认居中缩放产生的偏移 */ transform-origin: left center; }
如果需要消除缩放后图片周围多余的留白,可以配合调整margin负数值抵消偏移即可。
方案2:给每张图片套独立的fit-content容器
如果你需要周围布局适配图片缩放后的尺寸(不会保留原图片大小的占位空间),可以给每张图片单独包裹一个宽度自适应为图片原宽的容器,此时img的百分比宽度就是基于自身原宽计算的:
修改后CSS
.terms-of-service h2 { text-align: left; } .terms-of-service p { margin: 5px; padding-left: 5px; } .small-logos { display: flex; width: max-content; justify-content: space-evenly; /* 可选:调整flex项间距 */ gap: 8px; } /* 新增图片包裹层样式 */ .img-wrap { width: fit-content; } .img-wrap img { /* 此时50%就是基于图片自身原宽的比例 */ width: 50%; }
修改后HTML
<div class="terms-of-service col-content"> <h2>Terms of Service</h2> <p>This site uses cookies. By continuing to use this site you are agreeing to our use of cookies. Please refer to <a href="#">Google's Privacy Terms</a> and <a href="#">Terms of Service</a> to see how cookies are used.</p> <div class="small-logos"> <div class="img-wrap"><img src="https://www.sabico.com/wp-content/uploads/2012/12/slocaliza2.jpg" alt="BBB"></div> <div class="img-wrap"><img src="https://www.sabico.com/wp-content/uploads/2012/12/slocaliza2.jpg" alt="25y"></div> <div class="img-wrap"><img src="https://www.sabico.com/wp-content/uploads/2012/12/slocaliza2.jpg" alt="green"></div> <div class="img-wrap"><img src="https://www.sabico.com/wp-content/uploads/2012/12/slocaliza2.jpg" alt="Env"></div> </div> </div>
内容的提问来源于stack exchange,提问作者m3.b
相关产品推荐
相关产品推荐

