【问题标题】:Can't fit image in popup window if image is larger then window如果图像大于窗口,则无法将图像放入弹出窗口
【发布时间】:2021-11-10 23:23:36
【问题描述】:

我正在尝试制作一个简单的居中弹出 div 以在其中显示图像。弹出 div 应该具有图像大小,但是当图像大于页面窗口时,它会溢出其父级。我想在不使用 JS 的情况下将图像最大大小设置为窗口大小。

我正在尝试这样做,但它不起作用,有什么想法吗?

body {
    color: red;
}

.popup-window {
    padding         : 5px;
    background-color: aquamarine;
    display         : inline-block;
    position        : absolute;
    top             : 50%;
    left            : 50%;
    transform       : translate(-50%, -50%);
    max-width       : 100%;
    max-height      : 100%;
}

.popup-window>img {
    object-fit: contain;
}
<!doctype html>
<html>

<head>
    <title>This is the title of the webpage!</title>
    <link rel="stylesheet" href="mystyle.css">
</head>

<body>
    <div class="popup-window">
        <img src="https://conpeek.com/test/przod_auta.jpg">
        <!-- <img src="hubspot.png"> -->
    </div>
</body>

</html>

问题已解决

图像样式应如下所示:

.popup-window>img {
  max-width: 100vw; 
  max-height: 100vh;
}

然后当图像小于视口时,它具有自然尺寸,但是当它大于视口大小时,它会正确地适合视口。

【问题讨论】:

    标签: html css image dom popupwindow


    【解决方案1】:

    object-fit contains 是一个很好的方法,因为您可以确保可以完全看到图像。但要使其正常工作,img 元素必须设置宽度和高度(因此系统知道它试图在其中包含图像的内容)。如果没有这些设置,您只能获得自然尺寸的图像。

    body {
      color: red;
    }
    
    .popup-window {
      padding: 5px;
      background-color: aquamarine;
      display: inline-block;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      max-width: 100%;
      max-height: 100%;
     width: 100vw; /* added for demo */
      height: 100vh; /* added */
    }
    
    .popup-window>img {
      object-fit: contain;
      width: 100%;
      height: 100%;
    }
    <!doctype html>
    <html>
    
    <head>
      <title>This is the title of the webpage!</title>
      <link rel="stylesheet" href="mystyle.css">
    </head>
    
    <body>
      <div class="popup-window">
        <img src="https://conpeek.com/test/przod_auta.jpg">
        <!-- <img src="hubspot.png"> -->
      </div>
    </body>
    
    </html>

    【讨论】:

    • 但是在这种情况下,在你改变之后,图片变小了(我不明白为什么它设置在这个特定的尺寸上,为什么不是更大或更小的顺便说一句)。当图像大于页面窗口时,我想将其最大宽度和最大高度包装为页面窗口的 100%。像 max-width 或 max-height 这样的样式不起作用(我猜 beaceose 父级没有声明大小)所以这对我来说并不令人满意:(
    • 如果您希望弹出窗口覆盖视口,那么您可以将其设置为 - 我不确定我是否理解您希望它的大小。现在我将更改代码,以便弹出窗口填充视口。但是您是说您希望仅当图像的自然尺寸大于视口时才发生这种情况,否则您希望它更小?
    • 当图像小于视口时,图像应以自然尺寸显示,父弹出窗口应与图像大小相同(父项适合子项大小并具有填充空间),但当图像为大于视口的弹出窗口和图像应该具有最大 100%(减去父级填充)的视口大小。
    • 好的,您的更改将我指向最终分析器,我应该添加 max-width: 100vw;最大高度:100vh;图像样式,它可以按我的需要工作:) 我忘记了 vw 和 vh。谢谢 !如果您愿意,请更改您的代码,我会将您的答案标记为问题已解决
    猜你喜欢
    • 2010-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多