将图像居中在div内,无需绝对定位

时间:2016-06-29 17:00:55

标签: html css image

我试图在没有绝对定位的情况下将图像居中在div中,因为图像会溢出到页面上可能存在的任何其他div上。例如,我在容器div上方有一个div,它将包含按钮,但图像溢出到它上面。有没有办法在没有绝对定位的情况下使图像居中?

更多信息 - 我正在使用Electron。该图像实际上是base64编码的图像,它是从画布(canvas.toDataURL())中获取的,并使用IPC发送到主进程。在此之后,窗口的位置被改变为另一个html文件,并且当新页面被完全加载时,通过IPC发送请求以再次接收图像。然后将图像插入页面上的img标记。

$(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');
    });
});

设置src有效,但注释掉的代码不起作用(我试图使用div而不是img,但div的背景图像属性永远不会设置)。

Here's a JSFiddle of what I am trying to do。图像应该在内容div中居中,内容div,而不重叠菜单div。图像应垂直居中

2 个答案:

答案 0 :(得分:2)

如果它是内联元素,那么您可以使用text-align: center.

这是更新的Fiddle

答案 1 :(得分:1)

  

图片应该在内容div中居中[每个已删除的评论 显然是垂直和水平]并且只有内容div,而不会重叠菜单div。

Flexbox可以做到这一点

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>

相关问题