Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS - Make image fit screen so no scroll bars appear

Tags:

css

image

If you click to view a very big image that is higher than your screen res on google images, like this for example http://p1.pichost.me/i/32/1548022.png then it appears a + and - on cursor. The + makes the image have its original size, while the - makes the image fit the screen, but not the full screen, so that no scroll bars appear. I try to implement this last part on my css code but I didn't had much success, I tried setting overflow-x:hidden; and overflow-y:hidden; but this gives the original unscrollable size. What should I do? Ty

like image 749
darkchampionz Avatar asked Jan 25 '26 10:01

darkchampionz


1 Answers

It is easier if you use CSS background instead of the <img> element. We will use the background-size: contain property to achieve the sizing that you are looking for. With the exception of IE8, all recent modern browsers support this property-value combination.

p/s: You can change the dimensions of the image container as you please, but I'm using viewport units to best illustrate the example.

body {
  margin: 0;
  padding: 0;
  }
div.img {
  background-image: url('http://p1.pichost.me/i/32/1548022.png');
  background-position: center center;
  background-repeat: no-repeat;
  background-size: contain;
  width: 100vw;
  height: 100vh;
  }
<div class="img"></div>
like image 58
Terry Avatar answered Jan 28 '26 05:01

Terry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!