【问题标题】:Center an image inside a div without absolute positioning在没有绝对定位的情况下将图像居中在 div 内
【发布时间】:2016-06-30 01:23:30
【问题描述】:

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

更多信息 - 我正在使用 Electron。该图像实际上是从画布 (canvas.toDataURL()) 获取并使用 IPC 发送到主进程的 base64 编码图像。在此之后,窗口的位置被更改为另一个 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 重叠。图片应该水平居中垂直。

【问题讨论】:

    标签: html css image


    【解决方案1】:

    如果是内联元素,则可以使用text-align: center.

    这是更新后的Fiddle

    【讨论】:

      【解决方案2】:

      图像应居中 [每条已删除的评论 显然垂直和水平] 在内容 div 中,并且仅在内容 div 中,不与菜单 div 重叠。 p>

      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>

      【讨论】:

      • 有没有办法让内容 div 填满网页上的剩余空间,这样即使调整大小,图像也始终居中?
      • 是的,以全页大小查看演示。
      猜你喜欢
      • 2014-11-09
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 1970-01-01
      • 2013-04-20
      • 1970-01-01
      • 2011-07-29
      • 1970-01-01
      相关资源
      最近更新 更多