我遇到了一个问题,我需要将一个元素放置在图像上特定位置的图像顶部(比如距顶部 20%,距左侧 30%)。
我建议的解决方案是将图像包装在一个具有 relative
位置的 div 中,然后将位置为 absolute
的元素放在顶部和左侧 - 很简单。但经过多次尝试,我无法让它工作,这似乎是浏览器中的不同行为。
当您加载页面下方的 fiddle 时,虚拟图像将在您加载页面时起作用,但是,当您开始在 Chrome 或 Firefox 中展开或缩小结果窗口时,您将开始看到红色的 div
包含图像。这会导致点远离其预期点。这不会发生在 Safari 中。
所以问题是:我怎样才能始终将图像紧紧包裹起来?
更新:响应回答:包含图像的 div 必须是其父级大小的 100%,不能大于或小于父级。
fiddle :http://jsfiddle.net/12q26xu7/2/
html,
body {
height: 90%;
padding: 0;
margin: 0;
text-align: center;
}
.child-wrapper {
height: 50%;
}
.image-wrap {
position: relative;
height: 100%;
display: inline-block;
background: red;
border: 1px solid blue;
}
.image-wrap img {
max-height: 100%;
max-width: 100%;
width: auto;
height: auto;
vertical-align: middle;
}
.image-wrap .point {
position: absolute;
left: 20%;
top: 30%;
border-radius: 50%;
background: #000000;
width: 10px;
height: 10px;
}
<html>
<body>
<div class="child-wrapper">
<div class="image-wrap">
<img class="viewer__image" src="http://dummyimage.com/300">
<div class="point"></div>
</div>
</div>
</body>
</html>
最佳答案
让你的div的高度和宽度auto
:
.image-wrap {
position:relative;
height: auto;
width:auto;
display: inline-block;
background: red;
border: 1px solid blue;
}
编辑
根据你更新的问题,为了保持 100% 的高度但宽高比宽度,我认为你不能用纯 css 做到这一点,所以用下面的 js 应该做到这一点:
$('.image-wrap').each(function () {
var wrap = $(this),
image = wrap.children('img:eq(0)'),
ratio = image.width() / image.height();
wrap.data('ratio', ratio);
});
$(window).resize(function () {
$('.image-wrap').each(function () {
var wrap = $(this),
image = wrap.children('img:eq(0)'),
width = image.height() * wrap.data('ratio');
image.width(width);
wrap.width(width);
});
});
关于javascript - 将 div 包裹在 img 宽度周围并保持 div 100% 高,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31424658/