Centering Items with Flexbox and Overflow

Just remove the justify-content from your .container and add a margin: auto to your image.

.body {
  height: 600px;
}

.container {
  margin: auto;
  display: flex;
  /* align-items: center; // no need for this anymore */
  /* justify-content: center; // remove this */
  border: 1px solid red;
  height: 100%;
  overflow: auto;
}

img {
  border: 5px solid black;
  margin: auto;  /* add this */
}
<div class="body">
  <div class="container">
    <img src="http://placehold.it/700x700" />
  </div>
</div>

You can achieve this by wrapping your image in a container within a flex container, as follows:

  • Flex container
    • display: flex
    • height: 100vh
  • Inner container
    • margin: auto

This will allow you to get an image of unknown size centered in the viewport both vertically and horizontally, without losing the ability to scroll to any part of the image in case it doesn't fit inside the viewport in either direction.

Example 1: (Image centered in viewport)

body {
  margin: 0;  /* Override user agent styles */
}

.flex {
  display: flex;
  height: 100vh;
}
.container {
  margin: auto;
}
<body class="flex">
  <main class="container">
    <img src="http://placehold.it/100x100">
  </main>
</body>

Example 2: (Image doesn't fit in viewport, yet can still be scrolled)

body {
  margin: 0;  /* Override user agent styles */
}

.flex {
  display: flex;
  height: 100vh;
}
.container {
  margin: auto;
}
img {
  border: 1px solid red;
}
<body class="flex">
  <main class="container">
    <img src="http://placehold.it/1000x1000">
  </main>
</body>

It works in the latest version of Chrome, Firefox, Opera, and Edge.

Tags:

Html

Css

Flexbox