【问题标题】:Position absolute parent does not have width of child image in FireFox位置绝对父级在 FireFox 中没有子图像的宽度
【发布时间】:2019-10-26 20:38:00
【问题描述】:

问题

我希望<img> 的高度是其父级高度的100%,同时按比例缩放<img> 的宽度。当<img> 具有绝对位置并按预期工作时,这很容易做到。

*, *:before, *:after { box-sizing: border-box;}
body { margin: 0; }

.hero {
  border: 2px solid red;
  position: relative;
  min-height: 360px;
}

.content {
  /* Simulate content height */
  /* height: 500px; */
}

.background {
  border: 2px solid #2EA800;
}

img {
  border: 2px solid #0083FF;
  position: absolute;
  top: 0;
  right: 0;
  height: 100%;
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Example 1</title>
</head>
<body>
  <div class="hero">
    <div class="content">
      Hey there
    </div>
    <div class="background">
      <img src="https://via.placeholder.com/200x150" alt="">
    </div>
  </div>
</body>
</html>

但是,当它位于绝对位置的父级(图像容器)&lt;div&gt; 内时,父级的宽度计算不正确。

*, *:before, *:after { box-sizing: border-box;}
body { margin: 0; }

.hero {
  border: 2px solid red;
  position: relative;
  min-height: 360px;
}

.content {
  /* Simulate content height */
  /* height: 500px; */
}

.background {
  border: 2px solid #2EA800;
}

.background {
  position: absolute;
  top: 0;
  right: 0;
  height: 100%;
}

img {
  border: 1px solid red;
  height: 100%;
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Example 2</title>
</head>
<body>
  <div class="hero">
    <div class="content">
      Hey there
    </div>
    <div class="background">
      <img src="https://via.placeholder.com/200x150" alt="">
    </div>
  </div>
</body>
</html>

它应该如何工作

这只发生在 FireFox 中。在 Chrome 中,正如预期的那样,正确计算了图像容器的宽度。

JS Fiddle 中的代码示例(方便在其他浏览器中打开)

【问题讨论】:

  • 我在 Internet Explorer 上也看到过这个问题。在 Chrome 和 Safari 中似乎很好,但试图在height: 100% 上保持图像纵横比和比例会导致这种奇怪的定位
  • @Paulie_D,我已经编辑了上面的帖子以使用 sn-ps 和嵌入图像。只是等待同行批准

标签: html css image firefox css-position


【解决方案1】:

希望这会有所帮助。

.background img{
  float:right;
}

【讨论】:

  • 虽然这会将图像放置在正确的位置,但我不相信它会使image container 的宽度正确。如果在图像加载时图像容器被用作具有背景颜色的占位符,这可能是一个问题
  • 是的,就像@UsainBloot 说的那样。修复父级的位置而不是宽度,这是一个棘手的问题
【解决方案2】:

我刚刚在使用 Firefox 时遇到了这个问题,这简直是一场噩梦。

不过,我已经设法为我的用例解决了这个问题。

在我的例子中,我使用了一个需要 100% 高度的图像叠加层,然后我使用了一个 div 渐变来填充屏幕上的其余空间。在 chrome 中工作正常,因为外部绝对 div 保持图像的大小并自行调整。 Firefox 的行为就像图像是全高一样,所以我需要坐在图像旁边以形成无缝叠加的渐变不起作用。

Praveen 用他的浮动建议让我走上了正确的轨道,所以谢谢你 Praveen!

我通过在我的父容器上使用 flex 解决了这个问题,然后我将我的项目对齐到 flex end,所以它们都正确地堆叠在正确的位置。写下来听起来很简单,但这真是一个令人沮丧的错误!!!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-26
    • 2016-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多