CSS: How to make the background color of your text stop where the text stops...

... instead of spreading all across the width of the section that it is inside. Here's the easy way of getting this to happen, although the only way that it appears to work is with centered text. Just copy paste the code below at the end of the CSS attributes list:


h1 { display: table; /* keep the background color wrapped tight */ margin: 0px auto 0px auto; /* keep the table centered */ background-color:#HEXCODE or RGB+alpha; }


Instead of h1 you can have any text element. So, as an example I used it like this in a theme tweak:


.post-title {font-size:28px;font-weight:100;background: rgba(0, 0, 0, .5);display: table; /* keep the background color wrapped tight */margin: 0px auto 0px auto; /* keep the table centered */}


It would be nice to get this to work with non-centered text as well, of course. I have been hunting around, but they mostly seem to be offering solutions for centered text, some of which are quite a bit more complicated than what I have used. Anyway, here are the best ones that I have found:

https://stackoverflow.com/questions/14310154/how-do-i-set-a-background-color-for-the-width-of-text-not-the-width-of-the-enti


https://www.w3docs.com/snippets/css/how-to-add-a-background-color-for-the-text-width-instead-of-the-entire-element-width.html


Design Tip:
Adding a bit of padding (say 5 - 10 pixels) on the left and right of the text really helps, since otherwise the cut looks way too abrupt.
Powered by Blogger.