html - 响应式地将元素绝对定位在背景之上

标签 html css positioning absolute responsive

我想将三个元素保留在图像相应缩小时的同一位置。

.main
{
	position: relative;
}

.container
{
	display: inline;
}

.point
{
	display: inline;
    position: absolute;
	max-width: 15%;
	margin-right: 10px;
	padding: 3px 7px 3px 5px;
	font-size: 12px;
	font-weight: bold;
	color: #fff;
	background: #ff0000;
	border-radius(5px);
	box-shadow(1px 2px 5px rgba(0,0,0,0.5));
}

.one
{
	top: 40%;
	left: 10%;
}

.two
{
	top: 50%;
	left: 40%;
}

.three
{
	top: 75%;
	left: 20%;
}
<div class="main">
  <div class="container">
    <div class="point one">1</div>
    <div class="point two">2</div>
    <div class="point three">3</div>
  </div>
  <img src="https://i.ytimg.com/vi/M5SHKCxKDgs/hqdefault.jpg" alt="Husky">
</div>

最佳答案

我相信您希望它也随着图像响应地缩小而缩放,所以这实现了这种效果。

.wrapper {
      position: relative;
      display: inline-block;
    }
    
    .wrapper img { max-width: 100%; }
    
    .point
    {
      position: absolute;
    	max-width: 15%;
    	margin-right: 10px;
    	padding: 3px 7px 3px 5px;
    	font-size: 12px;
    	font-weight: bold;
    	color: #fff;
    	background: #ff0000;
    	border-radius(5px);
    	box-shadow(1px 2px 5px rgba(0,0,0,0.5));
    }
    
    .one
    {
    	top: 40%;
    	left: 10%;
    }
    
    .two
    {
    	top: 50%;
    	left: 40%;
    }
    
    .three
    {
    	top: 75%;
    	left: 20%;
    }
<div class="main">
  <span class="wrapper">
    <img src="https://i.ytimg.com/vi/M5SHKCxKDgs/hqdefault.jpg" alt="Husky">
    <span class="point one">1</span>
    <span class="point two">2</span>
    <span class="point three">3</span>
  </span>
</div>

我正在使用 inline-block 自动允许 wrapper 元素“环绕”图像,无论图像大小如何。我还设置了 max-width: 100% 以将图像变成响应式图像(好吧,它只是在窗口调整大小时按比例缩小)。由于这些点都是基于百分比的,因此它们会在图像缩小时保持在正确的位置。

✔ 无需固定宽度和高度的图像/包装器,因此响应迅速
✔ 需要更少的 HTML
✔ 除了不受支持的旧浏览器外,几乎可以在任何浏览器上工作

这是一个很好的技巧,我用它来做一些事情,比如跨图像的“横幅”和其他技术来将事物定位在图像上以获得效果。

关于html - 响应式地将元素绝对定位在背景之上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38517535/

相关文章:

html - 如何设计 Vkontakte 分享按钮看起来像 facebook 一样?

CSS帮助在底部重叠顶部

javascript - 在页面加载时随机定位 div

javascript - 将单词中的第一个字母大写表示正常状态

html - Chrome 中没有换行的文本区域

html - 仅更改 p 中一个字母的样式

css - 将两个元素定位在包装元素内

javascript - 如何创建多个表并在每个表中存储json数据

html - 列图像悬停文本

php - 全宽页脚 WordPress