0

The image in question is https://i.stack.imgur.com/bHrLR.jpg and it is 800px tall and 300px wide.

I used Flexbox to center it horizontally and vertically,

* {
  margin: 0;
  padding: 0;
}

body,
html {
  height: 100%;
}

body {
  display: flex;
  justify-content: center;
  align-items: center;
}
<img src="https://i.stack.imgur.com/bHrLR.jpg">

The codepen for above code is https://codepen.io/vbcda/pen/OJRvEpr (I suggest changing the editor layout where the output window takes the full sideways vertical space).

This works fine when the screen is large and its height is more than the image height but when the screen height is less than that of the image the top portion of the image gets cropped.

As for the bottom portion of the image it gets hidden behind a scrollbar when the height of the screen is less than the image.

While playing around with it I found that when I remove the height: 100% on the body, html it just sticks to the top as expected. So I could write a media query to do that but I am curious to know why this happens? Why does height: 100% on the body, html cause the top portion of the image to get cropped?

Wais Kamal
  • 5,858
  • 2
  • 17
  • 36
Vinith Almeida
  • 1,421
  • 3
  • 13
  • 32
  • If you give the body a height which is less than the height of the image AND you ask it to align center then it puts the center of the image (vertically) at the center of the body and so has to crop the top (and bottom) if 100% is less than 800px. If you remove the 100% then the body can fit the whole image in, starting at the top. – A Haworth Jan 04 '21 at 10:05

1 Answers1

-1

give it a height of 100vh. Then you can set the image height width as you need.

Adiat Hasan
  • 372
  • 3
  • 12