【问题标题】:Is there a foreground equivalent to background-image in css?css中是否有与背景图像等效的前景?
【发布时间】:2012-09-21 12:22:48
【问题描述】:

我想为网页上的元素添加一些亮点。如果我不必向页面添加额外的 html,我会更喜欢。我希望图像出现在元素的前面而不是后面。最好的方法是什么?

【问题讨论】:

  • 元素的尺寸是固定的吗?
  • 是的。更多字符让我发表评论。
  • 我正在尝试使它与 :after psuedo-element 现在一起使用...

标签: html css foreground


【解决方案1】:

要实现“前景图像”(无需额外的 HTML 代码),您可以使用伪元素 (::before / :before)加上 CSS pointer-events。最后一个属性是必需的,这样用户才能真正单击“好像它不存在”的图层。

这是一个示例(使用 Alpha 通道为 50% 的颜色,以便您可以看到真正的元素实际上可以被聚焦)。 http://jsfiddle.net/JxNdT/

#cont {
        width: 200px;
        height: 200px;
        border: 1px solid #aaa; /*To show the boundaries of the element*/
    }
    #cont:before {
        position: absolute;
        content: '';
        background: rgba(0,0,0, 0.5); /*partially transparent image*/
        width: 200px;
        height: 200px;
        pointer-events: none;
    }
    <div id="cont">
    Test<br>
    <input type="text" placeholder="edit">
    </div>

​ PS。我选择了::before 伪元素,因为这自然会导致正确的定位。如果我选择::after,那么我必须将position:relative; 添加到真实元素(#cont),并将top:0;left:0; 添加到伪元素(::after)。


PPS。要在没有固定大小的元素上获得前景效果,需要一个额外的元素。此包装器元素需要 position:relative;display:inline-block; 样式。将伪元素的widthheight设置为100%,伪元素会拉伸到包装元素的宽度和高度。演示:http://jsfiddle.net/JxNdT/1/.

【讨论】:

  • 好东西!由于图像已经具有 alpha 透明度,因此我不需要背景元素,但除了复制粘贴!
  • 只是好奇,如果元素大小不是静态的,是否有类似的解决方案?
  • @KristofferNolgren 你需要一个包含position:relative;(和display:inline-block;)的包装器,然后在伪元素上使用100% 来表示widthheight。伪元素将拉伸到包装元素的宽度和高度。演示:jsfiddle.net/JxNdT/1
  • @RobW 您不需要包装器,您可以拉伸绝对定位的:after 伪元素,并将 trbl 属性全部设置为 0;查看更新的小提琴:jsfiddle.net/JxNdT/2
  • 不错的解决方案!实际上,我必须使用 z-index 才能使其完全正常工作,但我猜这是针对我的情况
【解决方案2】:

一个简洁的解决方案:box-sizing + padding-left,在css-tricks查看更多内容

HTML 中的某处:

<img id="test_replacement" src="test.png" alt="test" />

替换图片的 CSS(悬停时)

#test_replacement {
    width: 200px; //must be the size of your image (and the replacement one)
    height: 200px; //idem
    display: block;
}
#test_replacement:hover {
    box-sizing: border-box;
    background-image: url('somewhere/other_image.png');
    padding-left: 200px; //at least the size of the width
}

【讨论】:

    【解决方案3】:

    如果你需要一个白色透明的前景

    这适用于像我这样正在考虑向元素添加白色透明前景以传达它已隐藏/禁用的未来访问者。您通常可以通过将opacity 降低到 1 以下来实现您的目标:

    .is-hidden {
        opacity: 0.5;
    }
    visible
    <span class="is-hidden">hidden</span>
    visible

    【讨论】:

      【解决方案4】:

      你可以使用这个css

      #yourImage
      {
      z-index: 1; 
      }
      

      注意

      z-index 设置为比您放置图像的元素的z-index 更大的索引。

      如果您没有指定任何z-index,那么1 将完成这项工作。

      您也可以将z-index 设置为-1,这样图片将始终位于background

      【讨论】:

      • z-index 属性仅适用于定位(absoluterelativefixed)元素。
      猜你喜欢
      • 1970-01-01
      • 2022-07-21
      • 2013-01-06
      • 1970-01-01
      • 2012-01-01
      • 1970-01-01
      • 2011-05-04
      • 2022-06-10
      • 2013-10-01
      相关资源
      最近更新 更多