在 FireFox 中,绝对父级位置没有子级图像的宽度

Ant*_*ins 5 html css firefox image css-position

问题

我希望 的高度<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%;
}
Run Code Online (Sandbox Code Playgroud)
<!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>
Run Code Online (Sandbox Code Playgroud)

实施例1

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

*, *: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%;
}
Run Code Online (Sandbox Code Playgroud)
<!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>
Run Code Online (Sandbox Code Playgroud)

实施例2

它应该如何运作

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

实施例3

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

小智 0

希望这会有所帮助。

.background img{
  float:right;
}
Run Code Online (Sandbox Code Playgroud)