【问题标题】:How can I make overlay buttons that always stay over the same part of the picture that is under them?如何制作始终位于其下方图片同一部分的叠加按钮?
【发布时间】:2022-02-11 11:24:05
【问题描述】:

我有一个有趣的问题或目标。我有一个黄色矩形的图像,里面有 3 个红色矩形。我想在图片顶部添加可点击按钮作为叠加层,就在红色矩形上方。

问题是,我希望这些按钮始终位于每个红色矩形上,大小/位置相同,无论图片的纵横比、用户的屏幕分辨率或浏览器的缩放百分比(如如果按钮是图像的一部分)

例如,我添加了一张图片,其中黄色矩形和红色矩形是同一图像的一部分,而绿色虚线是覆盖按钮或它们各自的 div。

[图片声望不够,但在这里]:https://i.imgur.com/ms4xmMZ.png

我的 HTML 到目前为止

<body>
    <div class="image-container">
        <img src="img/justelimage.png" alt="Nature" class="video" />

        <a href=“#”></a>

    </div>
</body>

我的 CSS 到目前为止可以工作,但应该有更好的方法吗? (当我调整窗口大小并改变浏览器的缩放百分比时有效,但是如果我们改变纵横比呢?)


.image-container {
    display: inline-block;
    position: relative;
    margin-left: auto;
    margin-right: auto;
    width: 80vw;
    height: auto;
    z-index:0;

}

.video {
    position: absolute;
    width: 100%;
    height: auto;
    z-index:1;
  
}

.image-container a{
    position: absolute;
    margin-top:4.5%;
    
    margin-left: 57%;
    width:28.3vw; 
    height: 7vw;
    color:white;
    border: 0.25vw solid green;
    z-index: 999;

}

}

知道如何以更合乎逻辑的方式实现这一点吗?

任何建议都将不胜感激。谢谢!

【问题讨论】:

标签: javascript html css responsive-design aspect-ratio


【解决方案1】:

我会将锚点包裹在一个 div 中以使其居中。这样你就可以风格 与 px 分别锚定,同时保持其相对于 img 的位置。

    <body>
      <div class="image-container">
       <img src="img/justelimage.png" alt="Nature" class="video" />
       <div class="link-container">
         <a href=“#”></a>
       </div>
      </div>
    </body>

    .link-container {
       position: absolute;
       top: 50%;
       left: 50%;
    }

如果您还使用背景颜色设置 .image-container 样式 和不透明度,您可以在 :hover 上切换这些值。

【讨论】:

    【解决方案2】:

    将按钮与图像保持在适当位置的最佳方法是将容器作为

    位置:相对;

    div 内的按钮为

    位置:绝对;

    并以px 或任何不随大小变化的单位放置在顶部和左侧。

    但是您可以做的一件主要事情是将您的图像作为image-container 的背景。 这样按钮始终位于图像顶部,您可以限制容器的大小调整以使按钮更好地保持在原位。

    我希望这会有所帮助。

    .image-container {
    position: relative;
      background-image: url("https://cdn.pixabay.com/photo/2014/12/28/13/20/wordpress-581849_960_720.jpg");
      background-size: contain;
      background-position: center;
      width: 600px;
      height:200px;
    }
    .btn{
    width:20px;
    height:20px;
    background-color: green;
    border:none;
    position: absolute;
    }
    .one{
        top:10px;
        left:300px;
    }
    .two{
        top:100px;
        left:100px;
    }
    .three{
        top:50px;
        left:200px;
    }
    <!DOCTYPE html>
    <html>
    <head>
    </head>
    <body>
    <div class="image-container">
    <button href="#" class="btn one"></button>
    <button href="#" class="btn two"></button>
    <button href="#" class="btn three"></button>
    
    </div>
    
    </body>
    </html>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-04
      • 1970-01-01
      相关资源
      最近更新 更多