【问题标题】:Make an overlay for a horizontally centered image without fixed width为没有固定宽度的水平居中图像制作叠加层
【发布时间】:2021-04-01 05:36:29
【问题描述】:

我有这个 HTML 结构:

<div class="container">
    <img class="image" />
    <div class="overlay">
       <div class="insides">more elements here</div>
    </div>
</div>

还有这个 CSS 代码:

.container {
  position: relative;
  height: 88vh;
  margin: 0;
}

.image {
  height: 100%;
  position: absolute;
  margin-right: auto;
  margin-left: auto;
  left: 0;
  top: 0;  
  bottom: 0;
  right: 0; 
}

.overlay {
  position: absolute;
}

我的要求如下:

  1. 使图像填充可用的垂直空间并将其水平居中。 (作品)
  2. 使图像覆盖与图像大小相同 - 不使用绝对 width 属性。 (不起作用 - 问题)
  3. 将图标固定到图像上的特定位置。 (对topleft 属性使用百分比......不确定这是否会像我目前认为的那样简单。)

我怎样才能拥有这一切 - 一个水平居中的图像展开以填充垂直空间,一个精确的叠加层和固定到图像特定位置的元素?

虽然我更喜欢 CSS hack,但也会考虑使用 Javascript 解决方案,以防需要以编程方式将图像的宽度转移到叠加层。

【问题讨论】:

    标签: javascript html css image overlay


    【解决方案1】:

    一种方法是将图像和叠加层包装在一个 div 中并将其居中。

    .container {
        position: relative;
        height: 88vh;
        margin: 0;
        text-align: center;
    }
    .imagecontainer
    {
        position: relative;
        display: inline-block;
        height: 100%;
    }
    .image {
        height: 100%;
    }
    .overlay {
        position: absolute;
        top: 0px;
        left: 0px;
        right: 0px;
        bottom: 0px;
    }
    <div class="container">
        <div class='imagecontainer'>
            <img class="image" src='imageurlhere'/>
            <div class="overlay">
               <div class="insides">more elements here</div>
            </div>
        </div>
    </div>

    像这样,Image 将设置其父级的宽度,同时设置 Overlay 的宽度。

    【讨论】:

    • 非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2013-11-14
    • 1970-01-01
    • 1970-01-01
    • 2014-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多