伪元素的背景图片未显示

15

我有一个带有三角形边框的 div 元素,我想使用 ::after 伪元素和 background-image 将图像放在它上面。但这种方法却行不通。然而,如果我尝试设置 content: "asd";,文本就会正确显示。基本上,我只想在那个三角形上方放置一张房子的图片。

以下是 HTML 代码:

<div id = "estatecorner" class = "house"></div>

这里是CSS代码:

#estatecorner {
  position: absolute;
  right: 0px;
  width: 0;
  height: 0;
  border-style: solid;
  border-width: 0 80px 80px 0;
  border-color: transparent #67b2e4 transparent transparent;
}

#estatecorner.house::after {
  position: absolute;
  width: 100%;
  height: 100%;
  background: url(images/mini/house.png);
  content: " ";
}

这里有一个jsFiddle


100% 的宽度/高度为0,因此您的伪元素宽度/高度为0,其背景图像不会显示。 - web-tiki
我将 #estatecorner 的宽度和高度设置为 100px,但仍然无法正常工作。 - Radu
really? - web-tiki
好的,现在它切割了三角形。我能避免这个吗?基本上我只想在那个三角形上面放一个房子图像。 - Radu
1
@Radu:这个(http://jsfiddle.net/hari_shanx/034pf1zv/3/)是你要找的吗? - Harry
1
是的,这正是我想要的!非常感谢!你能把它发布为答案,这样我就可以奖励你了吗?:D - Radu
3个回答

20

需要注意两点:

  1. 如评论中的web-tiki所提到的,伪元素的widthheight都设置为100%,而父元素的尺寸为0px x 0px(因为三角形是通过边框hack生成的)。因此,子元素(伪元素)的实际计算尺寸也为0px x 0px,因此图像无法显示。当您放置纯文本时,内容会显示出来,因为文本通常会溢出。解决这个问题的方法是为子伪元素分配显式的高度和宽度(为父元素分配高度和宽度会破坏边框hack)。

  2. 当将background-image分配给伪元素,并且图像的尺寸与容器(伪元素)相比较小时,背景图像会重复尽可能多的次数以适应容器元素。这应该避免使用background-repeat: no-repeat;并使用background-position属性在三角形内部定位图像,具体取决于需要使用的位置值的像素或百分比。

下面是最终的片段(包含高度、宽度和位置的示例值):

#estatecorner {
  position: absolute;
  right: 0px;
  width: 0;
  height: 0;
  border-style: solid;
  border-width: 0 80px 80px 0;
  border-color: transparent #67b2e4 transparent transparent;
}
#estatecorner.house::after {
  position: absolute;
  content: "";
  width: 80px;
  height: 80px;
  background: url("http://i.imgur.com/nceI30v.png");
  background-repeat: no-repeat;
  background-position: 75% 40%;
}
<div id="estatecorner" class="house"></div>

下面是另一种方法,使用旋转伪元素(CSS3变换)而不是边框技巧来实现三角形形状。

#estatecorner {
  position: absolute;
  width: 80px;
  height: 80px;
  right: 0px;
  overflow: hidden;
}
#estatecorner:before {
  position: absolute;
  content: '';
  top: -80px;
  right: -80px;
  height: 138.4px;
  width: 138.4px; /* (80 * 1.732px) */
  background: #67b2e4;
  transform: rotate(45deg);
  z-index: -1;
}
#estatecorner.house {
  background-image: url("http://i.imgur.com/nceI30v.png");
  background-repeat: no-repeat;
  background-position: 75% 35%;
}
<div id="estatecorner" class="house"></div>


3
请尝试这个:
 #estatecorner.house::after {
        content: url('../img/yourimage.jpg');
        position: absolute;
        left:0px;
        width: 100%;
        height: 100%;
    }

你的fiddle里的代码和答案中的代码一样吗? - Harry
不好意思,我已经修改了:请从 Fiddle 上获取 :) - Vinayak
修改后的解决方案很好,值得一票。请删除您的其他答案,因为它本质上是您自己答案的副本。 - Harry
是的,我已将其他答案删除。 - Vinayak

0

在这种情况下,您需要以像素而不是百分比为伪元素指定高度和宽度。

#estatecorner.house::after {
    position: absolute;
    width: 14px;
    height: 13px;
    background: url(http://i.imgur.com/nceI30v.png) no-repeat;
    content: " ";
    left: 50px;
    top: 20px;
}

原因#estatecorner的尺寸为0 x 0。因此,如果您将100%高度宽度赋予其伪元素,那么它们的尺寸最终也将为0 x 0,这将是无用的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接