html - 伪元素背景图片不出现

标签 html css pseudo-element css-shapes

我有一个带有三 Angular 形边框的 div 元素,我试图使用带有 ::after 伪元素在其上方放置一个图像背景图片。虽然该方法不起作用。但是,如果我尝试设置 content: "asd";,文本会正确显示。基本上我只想在那个三 Angular 形上方有一个房子图像。

这是 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

最佳答案

这里有两点需要注意:

  1. 正如 web-tiki 在评论中提到的,伪元素的 widthheight 被设置为 100%并且父元素的尺寸为 0px x 0px(因为三 Angular 形是通过 border hack 生成的)。因此,子元素(伪元素)的实际计算尺寸也是 0px x 0px,因此图像没有显示出来。当您放置纯文本时,内容确实会显示出来,因为文本通常会溢出。 此问题的解决方案是为子伪元素指定一个显式的高度和宽度(因为为父元素指定一个高度和宽度会破坏边框修改)。

  2. background-image 被分配给伪元素并且图像的大小与容器(伪元素)相比较小时,背景图像会重复多次尽可能适合容器元素。这应该通过设置 background-repeat: no-repeat; 来避免,为了将图像定位在三 Angular 形内,我们必须使用具有适当位置值的 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 转换)而不是边框​​ hack 来实现三 Angular 形的替代方法。

#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>

关于html - 伪元素背景图片不出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28646373/

相关文章:

html - CSS 折叠变换高度问题

javascript - 为什么我的文本显示为 "sd"?使用 Jquery 和 Post 将变量传递给 PHP

css - 丰富的面孔 : Is it possible to set the look of output text like input type password?

html - 哪些元素支持::before 和::after 伪元素?

css - 在 : numbers? 之前右对齐 CSS

javascript - 将 Javascript 库下载为图像?

html - 为移动设备调整堆叠列的高度 (@media)

css - 无法在 IE 中设置 HTML5 元素的样式(尽管有 shiv 并显示 :block)

css - css动画之间的平滑过渡

css - Firefox 怪癖 : select the first letter when an image is on the same line