Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make image in picture element fit its container

Tags:

html

css

I have the following code:

#container {
  background: steelblue;
  width: 333px;
  height: 333px;
}

picture img {
  object-fit: cover;
}
<div id="container">
  <picture>
    <img src="http://placekitten.com/g/300/300" alt="kitten">
  </picture>
</div>

How can I get the picture to fill the container box?

Here's a codepen.

like image 769
J86 Avatar asked Dec 19 '17 13:12

J86


1 Answers

You have to use display:flex in 'picture' element (in conjunction with object-fit property for the 'img')

This will work, for any size of the container.

like so:

#container {
  background: steelblue;
  width: 333px;
  height: 500px;
  
}
picture {
  width: 100%;
  height: 100%;
  display: flex;
 
}
picture img {
 object-fit: cover; 
    height: auto;
    width:100%;
}
<div id="container">
  <picture>
    <img src="http://placekitten.com/g/300/300" alt="kitten">    
  </picture>
</div>
like image 152
Jordi Flores Avatar answered Sep 19 '22 23:09

Jordi Flores