这是我想在纯CSS中完成的工作:
-
我给了我任意的
div
。我知道没有关于其布局的,除了,它的高度可以足够大,可以包含我将放入的内容。
特别是,绝对是明确的,这意味着我不知道其定位,填充,边距,宽度等。因此,解决方案中的任何内容都不应取决于其特定值。 -
我给了一个图像文件,其中包含任意维度的图像文件,要放置在
div
内(直接或间接(。 -
css应该缩小图像的规模,以确保其宽度不超过其父的宽度。
-
css应该将图像裁剪成一个圆。
最后,我应该看到一个圆形图像拟合到DIV而没有任何方面失真,其尺寸都不超过原始的尺寸。
这就是我理想世界中的样子:
<!DOCTYPE html>
<head>
<style type="text/css">
img {
max-width: 100%;
max-height: width; /* I wish this was a thing... */
border-radius: 50%;
object-fit: cover;
}
</style>
</head>
<body>
Arbitrary content...
<div style="width: 25%; margin-left: 10px; top: 1em;"> <!-- arbitrary -->
<img src="https://i.stack.imgur.com/8mNMb.png"/>
</div>
Arbitrary content...
</body>
</html>
现在显然这不起作用,因为您无法进行height: width
。
但是我该怎么办?我已经尝试了我能找到的书中的所有技巧,但是它们最终都以某种方式或其他方式失败了。这是height: 0; padding-bottom: 100%;
技巧的示例:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<style type="text/css">
.square {
height: 0px;
padding-bottom: 100%;
}
.circle {
position: absolute;
max-width: 100%;
height: 100%; /* not really sure what to put here */
border-radius: 0%;
object-fit: cover;
}
</style>
</head>
<body>
Arbitrary content...
<div style="width: 25%; margin-left: 50px; top: 1em;">
<div class="square">
<img class="circle" src="https://i.stack.imgur.com/8mNMb.png"/>
</div>
</div>
Arbitrary content...
</body>
</html>
我该如何实现?
您的第二个片段很近。您需要在方形容器上进行position:relative;
,因此可以设置圆的高度并具有100%的正方形容器。在IMG标签上使用object-fit: scale-down;
似乎是这样做的。
.circle {
height: 0px;
padding-bottom: 100%;
position: relative;
border-radius: 50%;
overflow: hidden;
}
.circle img {
position: absolute;
width: 100%;
height: 100%;
object-fit: scale-down;
}
Arbitrary content...
<div style="width: 25%; margin-left: 50px; top: 1em;">
<div class="circle">
<img src="https://i.stack.imgur.com/8mNMb.png" />
</div>
</div>
Arbitrary content...
<div style="width: 250px;">
<div class="circle">
<img src="https://picsum.photos/68/50" />
</div>
</div>
Arbitrary content...
<div style="width: 250px;">
<div class="circle">
<img src="https://picsum.photos/200/300" />
</div>
</div>
Arbitrary content...
<div style="width: 250px;">
<div class="circle">
<img src="https://picsum.photos/300/200" />
</div>
</div>
Arbitrary content...
<div style="width: 250px;">
<div class="circle">
<img src="https://picsum.photos/400/400" />
</div>
</div>
您可以大写以下事实:即使应用于 padding-top
和/或 padding-bottom
,基于百分比的adding始终是指父元素的width
。因此,您可以使用height: 0;
和padding: 50% 0;
工作以始终获得Square div
。
示例:
div div {
background: #ccc;
border-radius: 50%;
height: 0;
padding: 50% 0;
}
.a {
width: 20px;
}
.b {
width: 80px;
}
<div class="a">
<div></div>
</div>
<div class="b">
<div></div>
</div>
现在,您可以简单地将您选择的background-image
应用于div div
。