Johann
Johann

Reputation: 29867

Display image in full browser window but only scale down if image is too large

I want to display an image centered within the entire browser window. There are a few conditions though. If the image size fits within the browser's client area, display it at its original size. If the image is taller or wider than the browser client window, then scale the image down. Finally, if the user resizes the browser, the image will either scale down (if too large) or scale no larger than its original size if the browser window exceeds the image size.

I can do all this with jQuery but am wondering if it can be done using css alone?

EDIT:

The closest I've got is this:

https://jsfiddle.net/Deepview/o5vgo6du/

html

<div class="outerCont">   <img src="http://www.wonderslist.com/wp-content/uploads/2015/10/Doutzen-Kroes-Most-Beautiful-Dutch-Woman.jpg" /> </div>

css:

.outerCont {
  position: relative;
}

img {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  margin: auto;
   max-width: 100%;
    height: auto;
    width: auto;
}

But the image doesn't center vertically.

Upvotes: 0

Views: 66

Answers (2)

Johann
Johann

Reputation: 29867

Had to add the following to the outer div:

  width: 100vw;
  height: 100vh;

https://jsfiddle.net/Deepview/o5vgo6du/3/

Upvotes: 1

Tobias Glaus
Tobias Glaus

Reputation: 3628

Is that what you want to do? Just use background-size:cover and it will always fill the whole div.

*{
margin:0;
padding:0;
}
.image{
background:url('https://www.aussiespecialist.com/content/asp/en_gb/sales-resources/image-and-video-galleries/jcr:content/mainParsys/hero/image.adapt.1663.medium.jpg') no-repeat;
background-size:cover;
width:100vw;
height:100vh;
}
<div class="image"></div>

Upvotes: 0

Related Questions