如何将流体图像与相同大小的div元素叠加?

问题描述 投票:0回答:1

我有一张图片,我想要它:

  • 覆盖容器的最大空间,同时完全可见并保持纵横比
  • 与相同大小的
    div
    元素叠加

这是 HTML,非常基本:

<div class="container">
    <div class="image"><!-- Image is the background of this div -->
        <div class="overlay">
            <div class="dot"></div>
        </div>
    </div>
</div>

这是CSS:

html, body {
    height: 100%;
    background-color: #ddd;
}
.container {
    position: absolute;
    width: 80%;
    height: 80%;
    background-color: blue;
}
.image {
    position: relative;
    height: 100%;
    width: 100%;
    background-repeat: no-repeat;
    background-color: yellow;
    background-position: center;
    background-size: contain;
    background-image: url(http://dummyimage.com/70x40/000/fff.png)
}
.overlay {
    position: absolute;
    width: 100%;
    height: 100%;
}
.dot {
    position: absolute;
    top: 20%;
    left: 40%;
    width: 10px;
    height: 10px;
    background-color: red;
}

容器的图像覆盖是使用

contain
background-size
CSS 属性完成的。

问题是: 叠加层的尺寸错误(

.container
而不是
.image
),因此红点没有粘在相对于图像的位置。

演示:http://jsfiddle.net/GTLMP/

知道如何在没有javascript的情况下实现这一点吗?

一种解决方案是添加具有正确纵横比的包装

div
元素,然后
image
overlay
都可以是具有绝对全宽度和高度的内部元素,但是,我不知道如何在这样
div
将在容器中完全流动
div

其他解决方案,在此小提琴中演示:http://jsfiddle.net/K4UR4/3/,按照MilanSxD的建议,使用

inline-block
元素。部分有效:

  • 在 Chrome 中,即使初始状态为 Ok,垂直调整大小也会破坏包装器比例
  • 在 Firefox 中,不考虑图像的最大高度
html overlay css
1个回答
0
投票

在容器中添加:

display: inline-block;
© www.soinside.com 2019 - 2024. All rights reserved.