在尝试使图像适合矩形时,我遇到一个奇怪的问题,想知道是否有人知道为什么这三种使用对象适合度的行为方式不同:
.container {
width: 250px;
padding-top: 20%;
border: 1px solid red;
position: relative;
display:inline-block
}
.container>img {
position: absolute;
top: 0;
left: 0;
object-fit: contain;
object-position: center center;
}
.image {
width: 100%;
height: 100%;
}
.image-1 {
right: 0;
bottom: 0;
}
.image-2 {
right: 0;
bottom: 0;
max-height: 100%;
max-width: 100%;
}
<div class="container">
<img src="https://www.fillmurray.com/200/300" class="image">
</div>
<div class="container">
<img src="https://www.fillmurray.com/200/300" class="image-1">
</div>
<div class="container">
<img src="https://www.fillmurray.com/200/300" class="image-2">
</div>
从第一张图片可以看到-宽度和高度都可以正常工作。在第二张图像中,我尝试设置图像,使其以绝对定位而不是宽度和高度填充空间,但是这完全被忽略,图像只是溢出或保持其原始大小。
要解决此问题,我在第三个图像上使用了最大宽度和高度,但是这完全忽略了对象位置,并且不会增长到比其自身更大的宽度或高度。
为什么对象适合只能在声明的宽度和高度下工作,而如果图像仅占用坐标空间却不能,为什么对象位置不能在最大宽度和高度下工作?
答案 0 :(得分:1)
图片是已替换元素,因此无法像使用top
/ left
/ right
/ bottom
一样使用带有不可替换元素(例如简单的div
)。这是规范中的相关部分:
https://www.w3.org/TR/CSS2/visudet.html#abs-replaced-width
https://www.w3.org/TR/CSS2/visudet.html#abs-replaced-width
为了简化计算,图像的height
/ width
并未由top
/ bottom
和right
/ {{1 }}值,但它使用的是图片的默认图片,因此没有比率失真,left
不会执行任何操作。
为object-fit
/ bottom
使用不同的值,您将看到它们被忽略:
right
.container {
width: 250px;
padding-top: 20%;
border: 1px solid red;
position: relative;
display:inline-block
}
.container>img {
position: absolute;
top: 0;
left: 0;
object-fit: contain;
object-position: center center;
}
.image-1 {
right: 0;
bottom: 0;
}
基本上,<div class="container">
<img src="https://www.fillmurray.com/100/200" class="image-1" >
</div>
<div class="container">
<img src="https://www.fillmurray.com/100/200" class="image-1" style="right:100px;bottom:10000px">
</div>
<div class="container">
<img src="https://www.fillmurray.com/100/200" class="image-1" style="right:-10px;bottom:-10000px">
</div>
<div class="container">
<img src="https://www.fillmurray.com/100/200" class="image-1" style="right:-100px;bottom:50%">
</div>
/ top
只是在调整位置,并使用图像的固有尺寸。如果您明确指定宽度/高度或添加left
/ max-width
约束,则可以像已经进行的那样更改计算的max-height
/ height
。>
与输入元素Width of absolute positioned input doesn't follow CSS rules
相同的地方发生的相关问题在您的情况下,width
仅在第一种情况下起作用,因为您设置了object-fit
和height:100%
,所以比率失真。由于仅定义了width:100%
/ max-height
,因此第二种情况(如下所述)和第三种情况都不会发生,因此图像将仅遵循此约束并尝试保持其初始比率。
换句话说,max-width
仅在您更改宽度和高度并且此更改破坏了初始比率时才有效。仅更改其中之一或不更改将使object-fit
的使用无效。
相关问题:
CSS object-fit: contain; is keeping original image width in layout