>我有一个响应式背景图像,因此在调整屏幕大小时其宽度和高度会发生变化。在那个背景下,有一个绝对位置的元素。现在,我的问题是,在调整屏幕大小时,绝对定位的元素不会跟随其在背景图像上的位置......
这是我的HTML代码:
<section id="all">
<div id="clicked1">
<img class="box" src="factory.svg" width="100%" height="auto">
</div>
</section>
.CSS:
#all {
width: 100%;
height: 600px;
position: relative;
max-width: 1240px;
background: url('beach_to_meter.svg') no-repeat;
}
#clicked1 {
position: absolute;
left: 27%;
top: 28%;
z-index: 100;
width: 200px;
}
#clicked1 .box {
width:14vw;
max-width: 180px;
}
全屏是这样的:在此处输入图像描述但是当屏幕变小时,绝对定位的元素会移动,如下所示:在此处输入图像描述
如果您希望图像出现在另一个图像的确切位置上,您应该尝试 vw 和 vh(垂直宽度,垂直高度(,我记得做过这样的事情。如果这不能解决你的问题,你应该使用 px,并使用 javascript 检测屏幕的大小,以便你知道在哪里放置元素。
我认为 CSS 转换翻译在对齐元素方面很有帮助?也许你试一试?您可以定义小图片始终保持大图片高度的 25% 左右:
#clicked1 .box {
transform:translateY(25%);
transform:translateX(25%);
}
更多信息: https://www.w3schools.com/cssref/css3_pr_transform.asp.我没有你的图像源,所以我无法尝试。但希望这有帮助。
在背景图像上搜索绝对定位元素 我遇到了这个问题。希望我的询问能帮助到这里的人。
您可以使用CSS技巧的良好组合来获得一种行为良好的方式,在任何设备/显示器中将元素定位在图像上: 看看下面的片段
请注意,容器外的所有内容都是按vh
调整大小的,witch 是视口高度。这也可以通过vw
(视口宽度(来完成,我使用一些媒体查询来检测纵横比。
在容器内,您可以安全地使用百分比。看看.positioned
元素。元素大小为vh
(或vw
(,位置始终从左上角%
。
该代码段还使用巧妙transform: translate(-50%, -50%);
将容器居中置于视口中。
body {
background-color: #404040;/* optional, to see position */
}
.container {
background-image: url(https://i.stack.imgur.com/2EzPF.jpg);
background-size: cover;
height:90vh;
width:90vh;
background-repeat: no-repeat;
/* Center the container */
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%); /* magic of transform */
}
.positioned {
background-image: url(https://i.stack.imgur.com/jpkTo.png);
background-size: cover;
height:10vh;
width:10vh;
position: absolute;
top: 58%; /* Positioned on bottom left corner of factory*/
left: 33%; /* Positioned on bottom left corner of factory*/
opacity: 0.8; /* optional, to see position */
}
.positioned:hover {
background-image: none; /* optional, to see position */
}
@media (max-aspect-ratio: 1/1) {
/* css for vertical viewport */
.container {
height:90vw;
width:90vw;
}
.positioned {
height:10vw;
width:10vw;
}
}
<div class="container">
<div class="positioned"></div>
</div>