[英]How to contain image within a container with rounded corners?
即使您已将角圆角,原始 div 的边界框仍包括角 - 因此,如果您扩展图像以适合 div,它将扩展超过圆角。
由完美圆外接的完美正方形将始终是圆大小的 2/3。 您可以定义一个内部 div(正方形)和一个外部 div(圆形)。 然后,您可以将图像设置为包含在内部正方形内——这甚至适用于非正方形图像。
.outer { display: grid; place-items: center; width: 200px; height: 200px; border-radius: 50%; background: #aaa; } .inner { width: 66.66%; height: 66.66%; background: url('http://placekitten.com/300/300'); background-size: contain; background-repeat: no-repeat; background-position: center; }
<div class="outer"><div class="inner"></div></div>
为了优化圆圈内使用的空间,我们需要查看图像的纵横比。 例如,一个长但不是很高的图像应该尽可能多地占据圆圈的宽度。
此代码段读取图像的自然宽度和高度,并计算 x 或 y 方向是否适合最大可能。 它通过记住适合矩形的圆的直径与矩形(和 vv)的直径相同来做到这一点。
function scale() { const img = document.querySelector('.img'); const w = img.naturalWidth; const h = img.naturalHeight; const circle = document.querySelector('.circle'); let sizex = 'auto'; let sizey = 'auto'; let scale = circle.offsetWidth / Math.sqrt(w * w + h * h); if (w / h > 1) { sizex = w * scale + 'px'; } else { sizey = h * scale + 'px'; } circle.style.setProperty('--sizex', sizex); circle.style.setProperty('--sizey', sizey); } window.onload = scale; window.onresize = scale;
.container { width: 100vw; height: 80vmin; background-color: red; position: relative; } .circle { position: absolute; top: 40vmin; left: 20vmin; width: 50vmin; height: 50vmin; background-color: transparent; border-radius: 50%; border-style: solid; background-image: url(https://picsum.photos/id/1015/300/400); background-repeat: no-repeat; background-position: center center; background-size: var(--sizex) var(--sizey); background-color: white; } .img { opacity: 0; position: absolute; }
<img class="img" src="https://picsum.photos/id/1015/300/400" /> <div class="container"> <div class="circle"> </div> </div>
该代码段有点基础,例如,如果您事先知道尺寸,则可以让 CSS 进行计算,而无需加载 img 来查找其自然宽度/高度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.