I'm trying to put a background image on a div that is using CSS borders to create a triangle. This is my current efforts so far. It works fine with solid colours, but I am at a loss when it comes to images.
HTML
<div class="wrapper">
<div class="left triangle"></div>
<div class="right triangle"></div>
</div>
CSS
.wrapper {
padding:50px 0px;
height: 50px;
position: relative;
width: 300px;
background: url("http://4.bp.blogspot.com/-dq50t26bK1o/TruhUtyIBWI/AAAAAAAANEw/kKnBQ1lSGik/s1600/bokeh_texture04.jpg");
}
.triangle {
border-bottom: 50px solid #eee;
width: 50px;
position: absolute;
bottom: 0;
}
.right {
right: 0;
border-left: 100px solid transparent;
}
.left {
left: 0;
border-right: 100px solid transparent;
}
jsfiddle: http://jsfiddle.net/aRS5g/9/
so, looking at that JS Fiddle, how would i make that gray section also an image background of my choice, rather than having to use colours such as #111, #eee, etc..
A triangle in CSS is a hack, created by displaying parts of the border of an element. Therefore, the triangle that you see is not an element itself, but a CSS border.
The border cannot be styled using the normal CSS background-image
style, and this is where you start seeing the limitations of CSS triangles, and why it really is a hack rather than a good technique.
There is a CSS solution that may work for you: border-image
.
border-image
is a CSS style that does what you'd expect; it puts an image into the border of an element. Since the CSS triangle is a border, you could use it to put a background image onto your triangle.
However, things do get complicated. The border-image
style is designed to style borders, not triangles; it has features for styling corners and sides, and stretching images appropriately. I haven't tried it with a triangle, but I can predict that it may have some quirks that make it tricky to use. But feel free to give it a go.
The other problem with border-image
is browser support. It's a relatively new CSS style, and is completely unsupported in many current browsers, including all versions of IE. You can see the full browser support table for it at CanIUse.
Because of all these issues, I would suggest that if you want to draw shapes in the browser, you really should consider dropping CSS hacks, and using SVG or Canvas. These are well supported in most browsers, and obviously support all the drawing features you could possibly want.
CSS triangles are great for making the occasional arrow shape, but for anything more complex than that it's a lot easier to use proper graphics rather than trying to pile more and more hacks into your CSS code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With