Eternity Eternity - 5 months ago 9
HTML Question

Center an image inside a div without absolute positioning

I am trying to center an image inside a div without absolute positioning, because the picture overflows onto any other div that might be on the page. For example, I have a div above the container div which will contain buttons, but the image is overflowing onto it. Is there any way to center the image without absolute positioning?

Some more information - I am using Electron. The image is actually a base64 encoded image which was taken from a canvas (

canvas.toDataURL()
) and sent to the main process using IPC. After this, the window's location is changed to another html file, and when the new page is fully loaded, a request is sent via IPC to receive the image again. The image is then inserted into an img tag on the page.

$(document).ready(function() {
ipcRenderer.send('display-snap');
ipcRenderer.on('reply-snap', (event, arg) => {
$("#snapshot").attr("src", arg);
//$("#snapshot").css('background-image', 'url(' + arg + ') no-repeat center center');
});
});


Setting the src works, but the commented out code doesn't work (I was trying to use a div instead of an img, but the background image property of the div is never set).

Here's a JSFiddle of what I am trying to do. The image should be centered in the content div and only the content div, without overlapping the menu div. The image should be centered horizontally and vertically.

Answer

The image should be centered [per deleted comment apparently both vertically and horizontally] in the content div and only the content div, without overlapping the menu div.

Flexbox can do that

html, body {
    width:100%;
    height:100%;
    overflow:hidden;
    margin:0;
    padding: 0;
}

#menu {
    height: 64px;
    background-color: red;
}

#container {
  height:100%;
  }

#content {
  display: flex;
  height:calc(100% - 64px);
  justify-content: center; /* center horizontal */
  align-items: center; /* center vertical */
  overflow: hidden;
  background:#c0ffee
}
<body>
  <div id="container">
    <div id="menu">
    
    </div>
    <div id="content">
      <img id="snapshot" src="http://www.fillmurray.com/g/200/200" />
    </div>
  </div>
  <script src="scripts/window.js"></script>
</body>