How to make an image always 100% width but adjust the height and keep the aspect ratio?

I know this must have been asked before but I just cannot find any css to help me. How do I make an image always 100% height and 100% width to match the screen size but always keeping the image’s aspect ratio?

.myimage {  
object-fit: cover;
width: 100%;
height: 250px;
}

Above almost works but I don’t want to hard code height and would like to almost be 100% of the browser’s view but keeping the aspect ratio. So the image should always fit 100% height and width wise without any scrolling and maintain that even if the browser is resized. I am using boostrap-5 framework.

>Solution :

.myimage {
  object-fit: cover;
  width: 100vw;
  height: 100vh;
  display: block;
}

html, body {
  margin: 0;
  padding: 0;
}
<img class="myimage" src="//placekitten.com/400" />

Leave a Reply