I thought I’d jot down a snippet of CSS I came up with recently that I use to generate UI ribbons. The code uses :before/:after
pseudo elements, which means it works in IE8+ and all the other not-shitty browsers. To ensure the content of the ribbon can be modified dynamically using JavaScript, I’ve set the pseudo element’s content
property with the value attr(ribbon)
. The attr()
content function grabs the parent element’s ribbon HTML attribute string (example: ribbon="SomeText"
) and uses it for the ribbon’s content. I’m pretty sure this is one of, if not the, shortest bit of code required to create CSS ribbons, but perhaps you all can improve upon it:
.ribbon:before { display: block; content: attr(ribbon); background: #eee; } .ribbon:after { display: block; content: " "; border-left: 5px dotted transparent; border-top: 5px solid #ccc; height: 0; width: 0; }
Hello,
This seems interesting, but there must be something wrong with the HTML in the example:
ribbonElement.setAttribute(‘ribbon’, )
Best Wishes,
Per Q A
No, the line of HTML your are citing is not the ribbon, that’s just a little presentational stuff to show what the JS would be you would use to change the value. Try typing in the input and it will change the ribbon value 😉
Is there a reason you chose to use an attribute for the content rather than actual text that’s also available in javascript? Also, should you use data-ribbon as the attribute name to avoid collision with any future potential ribbon attribute in the W3C standards?
I chose to use an attribute because you can set the ‘content’ property value of before/after pseudo elements to ‘attr(SOME_ATTRIBUTE)’ it changes the content for you dynamically with just CSS (this it is easily overrode with user styles). Pseudo elements were required to provide the structure and triangle anyway; also, setAttribute is compatible with IE8, where as the DOM method ‘textContent’ was not introduced until IE9, so a slight compatibility bump as well. Feel free to change it to whatever you want though 🙂