我有一个带有三 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
最佳答案
这里有两点需要注意:
正如 web-tiki 在评论中提到的,伪元素的
width
和height
被设置为100%
并且父元素的尺寸为 0px x 0px(因为三 Angular 形是通过 border hack 生成的)。因此,子元素(伪元素)的实际计算尺寸也是 0px x 0px,因此图像没有显示出来。当您放置纯文本时,内容确实会显示出来,因为文本通常会溢出。 此问题的解决方案是为子伪元素指定一个显式的高度和宽度(因为为父元素指定一个高度和宽度会破坏边框修改)。当
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/