【问题标题】:How to add a background square behind the image?如何在图像后面添加背景方块?
【发布时间】:2020-04-28 18:26:40
【问题描述】:

我正在尝试重新创建这个:

但我没能做到。我尝试在 img 上添加 :before 但这不起作用。你会怎么做这个。它必须以背景不大于图像的方式进行响应。

搜索引擎优化并不重要,所以 background-image 或任何对我来说都很好的东西。

用 SCSS 编写 - 可以更改 HTML

ROB 答案的更新代码

这是我目前的代码

.imgbox {
        padding: 5%;
        position: relative;
        height: auto;

        .backdrop {
            position: relative;
            min-width: 100px;
            min-height: 100px;

            div {
                position: absolute;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                max-width: 100%;
                max-height: 100%;
                background: rgb(208, 0, 0);
                background: linear-gradient(
                    90deg,
                    rgba(208, 0, 0, 1) 0%,
                    rgba(149, 0, 0, 1) 100%
                );

            }
                transform: translateX(-5px) translateY(5px);
        }

        .img {
            width: 100%;
            height: auto;
            transform: translateX(5px) translateY(-5px);
        }
    }
        <div className="imgbox">
            <div className="backdrop">
                <div></div>
            </div>
            <img
                className="img"
                src={'https://source.unsplash.com/400x250'}
                alt="test"
            >
        </div>

【问题讨论】:

  • 您的 HTML 无效。没有自我关闭&lt;div /&gt; 这样的东西。此外,&lt;img&gt; 标签不使用也不需要结束斜杠,在 HTML 中也从来没有。
  • 即使我修复了它,它也不起作用
  • 你为什么不在 上使用阴影。可以使用box-shadow generator 轻松创建?
  • 背景框有线性渐变,不能用框阴影制作
  • 如果您需要渐变,请查看stackoverflow.com/questions/61475188/…

标签: html css sass


【解决方案1】:

盒子阴影很简单。

父级中的填充是为了防止它裁剪阴影。

.imgbox {
  padding: 0 0 30px 30px;
}

.imgbox .img {
  display: inline-block;
  box-shadow: -30px 30px 0 rgb(208, 0, 0);
}
<div class="imgbox">
      <img
          class="img"
          src='https://source.unsplash.com/400x250'
          alt="test"
      />
</div>

【讨论】:

  • 尽管线性渐变在这方面不起作用,但你一直是这方面唯一有帮助的人。谢谢你。我将使用它以防万一,因为它非常容易集成和响应。
【解决方案2】:

使用pseudo-element 很容易获得渐变:

.image-container::after {
  content:'';
  position: absolute;
  z-index:-1;
  bottom:-24px;
  left:-24px;
  width:100%;
  height:100%;
  background: linear-gradient(red, firebrick); 
}

您可以分别使用backgroundleftbottom 更改渐变和偏移。我不确定右上角是否还有第二个渐变?如果是这样,您将其与::before 配对以获得第二个背景,并与z-index 一起玩以获得正确的排序。

请记住 - 要使绝对定位的伪元素起作用,您需要在父容器上设置 position:relative,并在 content:'' 上设置;

Codepen here.

【讨论】:

  • 谢谢,这完全符合我的要求,响应迅速且简单。太好了!
猜你喜欢
  • 2017-04-24
  • 2021-09-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-17
  • 2012-11-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多