【发布时间】: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>
但是,当它位于绝对位置的父级(图像容器)<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%;
}
<!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