0

Need some help with image placement. I want my picture to float to bottom right corner and in case image size doesn't match window inner width or height, fill window with said image without changing aspect ratio. To explain it more thorough I'm adding a picture: Explanation.

Tried different approaches but all of them failed:

  • Using width:100% and height:100% for "img" in CSS (issue being image aspect ratio change depending on window size)
  • Using height:100% for "img" in CSS and changing "img" margin-left with JavaScript( setting left margin equal to window.innerWidth - document.getElementById("image.png").width pixels) to cut one of the sides off (issue being that resized image sometimes lacks width to begin with and couldn't get proper margin values)

Tried running through a lot of similar posts in "stackoverflow" but couldn't find one that helps.

  • 1
    There are many posts about this. Have you looked at [this one](https://stackoverflow.com/q/3751565/215552) or [this](https://stackoverflow.com/q/3029422/215552)? Note that you should look at answers other than the accepted one; often people answer after acceptance and they can be much simpler. – Heretic Monkey Feb 20 '19 at 22:42

1 Answers1

2

You can use CSS properties object-fit and object-position. Let's say you have the following layout:

<div class="container">
  <img class="img" src="http://some-img"></img>
</div>

For this example you should put the following styles:

.img {
   width: 100%;
   height: 100%;
   object-fit: cover; /* save your aspect ratio */
   object-position: right bottom; /* put your image to the right corner */
}

The live demo can be found at CodePen

Dmitry Chebakov
  • 348
  • 3
  • 11