Home > Mobile >  Align everything to the top when used object-fit: contain;
Align everything to the top when used object-fit: contain;

Time:05-30

I'm trying make an image occupy entire view area while retaining its aspect ratio. object-fit: contain; seems to do the trick, except regardless of the window size, the image occupy entire height, pushing everything outside of view area.

.resize img
{
  width: 100%;
  height: 100%;
  object-fit: contain;
  object-position: 50% 0;
}

.resize
{
  overflow: auto;
  resize: both;
  border: 2px solid red;
}
<div  style="width:100px;height:170px;">
  <span>
    <img src="https://lh3.googleusercontent.com/taykG37GWDgY-FGkdogDvsHSJMUGRMvkuVRT6yR-5UNkKvGRKeRlpGYXlslocOcS0txlfUdGW59JGtzADknxbMqnh6AtVCv9EXyB8nHp80YsRNA0Yw=w1024-h683-n-l50-sg-rj">
  </span>
  <div>myText</div>
</div>

How can I make the image fit into view area (red box), without leaving empty space below it?

Expected Result Actual Result
expected actual
expected expected

CodePudding user response:

span {
    text-align: center;
    float: left;
    width: 100%;
}
.resize img
{
    width: inherit;
    height: min-content;
    object-fit: scale-down;
    object-position: 50%;
    margin: 0 auto;
    position: relative;
    max-width: 350px;
    max-height: max-content;
}

.resize
{
 overflow: auto;
resize: both;
border: 2px solid red;
min-height:250px;
}
    <div  style="width:100px;">
      <span>
        <img src="https://lh3.googleusercontent.com/taykG37GWDgY-FGkdogDvsHSJMUGRMvkuVRT6yR-5UNkKvGRKeRlpGYXlslocOcS0txlfUdGW59JGtzADknxbMqnh6AtVCv9EXyB8nHp80YsRNA0Yw=w1024-h683-n-l50-sg-rj">
      </span>
      <div>myText</div>
    </div>

CodePudding user response:

Use CSS grid to define two rows, one for the image and the other for the text

.resize img {
  width: 100%;
  height: 100%;
  object-fit: contain;
  object-position: 50% 0;
}

.resize {
  overflow: auto;
  display: grid;
  grid-template-rows: minmax(0,1fr) auto;
  resize: both;
  border: 2px solid red;
}
<div  style="width:100px;height:170px;">
  <img src="https://lh3.googleusercontent.com/taykG37GWDgY-FGkdogDvsHSJMUGRMvkuVRT6yR-5UNkKvGRKeRlpGYXlslocOcS0txlfUdGW59JGtzADknxbMqnh6AtVCv9EXyB8nHp80YsRNA0Yw=w1024-h683-n-l50-sg-rj">
  <div>myText</div>
</div>

  •  Tags:  
  • css
  • Related