Search code examples
csssize

Image CSS sizing (to fit in screen) works different in Firefox and Chromium


The following code works as intended in Firefox: the image fits the available screen space, with no scrollbars. In Chromium, however, when the window is not high enough a vertical scrollbar is shown and the image moves 1px up or down.

What is the cause of this and how can it be fixed (other than using e.g. calc(100% - 1px) instead of 100%)?

* {
  box-sizing: border-box;
  margin: 0;
}

body {
  height: 100vh;
  display: grid;
  grid-template-rows: auto 1fr auto;
  background-color: white;
  color: black;
}

.head {
  text-align: center;
}

.body {
  height: 100%;
  overflow: auto;
  display: grid;
  grid-template-columns: auto 1fr auto;
}

.left, .right {
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  font-size: 300%;
  background-color: rgba(0,0,0,0.2);
  height: 1em;
  width: 1em;
  margin: auto 0.1em;
  border-radius: 0.5em;
}

.center {
  text-align: center;
  min-width: 0;
  min-height: 0;
  overflow: auto;
}

.center img {
  vertical-align: text-bottom;
  max-width: 100%;
  max-height: 100%;
  padding: 0.2em;
}
<div class="head">
HEAD<br/>BLOCK
</div>

<div class="body">
<div class="left">L</div>
<div class="center">
<img src="https://placehold.co/1200x900" />
</div>
<div class="right">R</div>
</div>


Solution

  • You need to change overflow value to hidden in .center class selector.

    .center {
      text-align: center;
      min-width: 0;
      min-height: 0;
      /*This is wrong
        overflow: auto;
      change to*/
      overflow-y: hidden;
    }
    

    Edit: If you wish to keep overflow: auto;, then the issue is with vertical-align in .center img {...}. Changing value to middle or bottom solves the issue:

    .center img {
      vertical-align: middle;
      max-width: 100%;
      max-height: 100%;
      padding: 0.2em;
    }
    

    See live behaviour and documentation here