Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
450 views
in Technique[技术] by (71.8m points)

css - object-fit, object-positioning and absolute positioning

Whilst trying to make an image fit into a rectangle, I came across a weird problem and wondered if anyone knew why these three ways of using object fit act differently:

.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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The image is a replaced element so the use of top/left/right/bottom will not work like it will do with a non-replaced element (a simple div for example). Here is the relevant parts from the specification:

https://www.w3.org/TR/CSS2/visudet.html#abs-replaced-width

https://www.w3.org/TR/CSS2/visudet.html#abs-replaced-height

To make it easier the computed height/width of your image aren't defined by the top/bottom and right/left values but it's using the default one of the image thus there is no ratio distortion and object-fit will do nothing.

Use different value for bottom/right and you will see that they are ignored:

.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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...