css - 对象拟合、对象定位和绝对定位
问题描述
在尝试使图像适合矩形时,我遇到了一个奇怪的问题,想知道是否有人知道为什么这三种使用对象适合的方式会有所不同:
.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>
正如您从第一张图片中看到的 - 一切都适用于宽度和高度。在第二个图像中,我尝试设置图像,使其以绝对定位而不是宽度和高度填充空间,但这完全被忽略了,图像只是溢出或保持其原始大小。
为了解决这个问题,我在第三张图像上使用了最大宽度和高度,但这完全忽略了对象位置,并且不会增长到比自身更大的宽度或高度。
为什么对象适合仅适用于声明的宽度和高度,而不是如果图像只是占用坐标空间,为什么对象位置不适用于最大宽度和高度?
解决方案
图像是一个替换元素,因此使用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-height
为了更容易计算图像的height
/width
不是由top
/bottom
和right
/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
就像您已经做过的那样。
输入元素发生同样情况的相关问题:绝对定位输入的宽度不遵循 CSS 规则
在您的情况下object-fit
,仅适用于第一种情况,即自您设置height:100%
和以来我们有比率失真width:100%
。第二种情况(如上所述)和第三种情况都不会发生任何事情,因为您只是定义了max-height
/max-width
因此图像将简单地遵循此约束并尝试保持其初始比率。
换句话说,object-fit
仅当您更改宽度和高度并且此更改破坏了初始比率时才会起作用。仅更改其中一个或一个都不更改会使使用object-fit
无用。
相关问题:
推荐阅读
- spring - 如何从 Spring Boot 应用程序提供 React 应用程序?
- android - 在 xamarin android.ui 中启动双卡设置页面
- kotlin - 向 Uri、Kotlin 添加特殊字符
- c# - EF 6 添加后获取实体
- perl - 从今天日期减去天数并在之后进行比较
- python - 单元测试“失败”方法无法找到对测试类的引用
- java - 使用 ProcessBuilder 运行 docker-compose up 成功,但 ProcessBuilder 不返回结果
- bash - 回显后不显示输出
- adobe-indesign - 如果 TextFrame == "Test" 存在,则复制或复制页面
- android - 房间实体默认值 VS 辅助构造函数