I have a div
element with a triangle-border and I'm trying to place an image above it using an ::after
pseudo-element with background-image
. The method doesn't work though. However if I'm trying to set content: "asd";
, the text appears correctly. Basically I just want to have a house image above that triangle.
Here's the HTML code:
<div id = "estatecorner" class = "house"></div>
And here's the 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: " ";
}
Here's a jsFiddle
You need to give the height and width of the psuedo elements in px and not in % for this case.
The reason is that
#estatecorner
have dimensions of 0 x 0. So, if you give 100% height and width to its psuedo elements then their dimensions will eventually be 0 x 0 too which would be useless.There were two things to take note of here:
As web-tiki had mentioned in comments, the
width
andheight
of the pseudo-element were set to100%
and the parent element had dimensions of 0px x 0px (because the triangle was generated through border hack). Because of this the actual calculated dimensions of the child (pseudo-element) were also 0px x 0px and hence the image was not showing up. The content did show up when you put plain text because text typically overflows. The solution to this problem is to assign an explicit height & width to the child pseudo-element (as assigning a height & width to the parent would spoil the border hack).When
background-image
is assigned to a pseudo-element and the size of the image is small compared to the container (pseudo-element), the background image is repeated as many times as possible to fit the container element. This should be avoided by settingbackground-repeat: no-repeat;
and to position the image within the triangle we have to use thebackground-position
property with the appropriate position values in pixels or percentages depending on the needs.Below is the final snippet (with sample values for height, width & position):
The below is an alternate approach using a rotated pseudo-element (CSS3 transforms) instead of the border hack to achieve the triangle shape.
Please try this;