好的,所以我想放置在另一个具有背景图像的 div 之上。 image-div 具有以下属性:
position: absolute;
top:0;
left:0;
width:100%;
height:100%;
background-image: url('../img/1.jpg');
background-size: contain;
background-repeat: no-repeat;
background-position: center center;
这看起来像我想要的所有设备。但现在我需要用适合图像特定部分的可点击 div 覆盖 image-div。让 div 适合很容易,只需将位置设置为绝对位置并设置顶部、左侧、宽度和高度,但只要我以另一种分辨率/密度显示,div 就会偏离,这并不奇怪。所以我尝试使用 % 或 vh 和 vw 进行定位,但似乎没有任何效果。
无论使用何种设备、分辨率和密度,我如何将 div 定位在图像之上?
最佳答案
它是 background-position
、background-size
和包含 div 的百分比偏移量的组合。
将 background-position
保持在特定值,以便图像上的点始终在屏幕上。
使用 background-size: cover;
或 background-size: contain;
使图像(或其容器)保持响应。
如果图像的外边缘有两个或更多点,我建议使用 contain
,但这会在较小的屏幕上显着减小图像大小,而内部 div 将保持相当大。
在其他情况下,使用 cover
来调整大小。
我在这里创建了一个示例:(我使用 Jquery UI 使图像可调整大小)
$( function() {
$( "#resizable" ).resizable();
} );
.container {
background-image: url('https://images.unsplash.com/photo-1465218550585-6d069382d2a9?dpr=1&auto=format&fit=crop&w=1500&h=994&q=80&cs=tinysrgb&crop=');
background-size: cover;
background-position: 50% 50%;
height: 500px;
position: relative;
width: 800px;
}
.hit-me-container {
height: 16px;
left: 52%;
position: absolute;
top: 45%;
width: 16px;
}
.hit-me {
animation: pulse 1s ease infinite;
background-color: #fff;
border: 3px solid #777;
box-sizing: border-box;
border-radius: 50%;
cursor: pointer;
height: 100%;
width: 100%;
}
.hit-me-container:hover:after {
background-color: #333;
color: #fff;
content: 'Buy these glasses';
display: block;
font-family: sans-serif;
font-size: 12px;
left: 20px;
padding: 5px;
position: absolute;
width: 100px;
top: -4px;
}
@keyframes pulse {
0% { transform: scale(1); }
50% { transform: scale(1.1); }
100% { transform: scale(1); }
}
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="container" id="resizable">
<div class="hit-me-container">
<div class="hit-me"></div>
</div>
</div>
或者检查这个fiddle
关于javascript - 将 div 置于图像顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41635634/