Bear with me here, but assuming this code:
<style>
span {
color: black;
background-color: black;
}
</style>
<span>Hello world</span>
Hello world
Gives a result that looks like this:
███████████
Is it possible to apply style to just the letter height, versus the font/line height? In effect ending up with something that looks like this:
█▄██▄ ▄▄▄██
No (not with a background color anyway). Background colors apply to the entire element (e.g., span element), which is essentially a box as determined by the CSS box model. The official recommendation from the W3C specifies that a background color will fill the content, padding, and border areas of the box model. The CSS3 background (candidate recommendation) offers a bit more power for you to control where background colors apply, but not much.
If you really want the effect you've just demonstrated in your question, I think a JavaScript function to convert "short" characters (e.g., "w") to "▄" and "tall" characters (e.g., "h") to "█" would work nicely. Here's a demo on jsfiddle.
I can't think of a way using ONLY CSS, but you could use a function in PHP like imagefontheight: http://php.net/manual/en/function.imagefontheight.php and dynamically create your block elements from the specified font...
The only way I can think of to get the effect purely by CSS requires:
In other words: it really better be well worth the effort, and it probably ought to be used on only a very short string of text.
Here's an example fiddle with the word color left contrasting to see how the background fits the letters. Note: this undoubtedly will have some variation on height and spacing above/below letters based on browser and font's being seen by you. The use of a :before
pseudo-element to achieve the effect means accommodations would need to be made for older browsers (IE7 and under).
Here's the basic code in the fiddle.
<span>H</span><span class="short">e</span><span>l</span><span>l</span><span class="short">o</span><span class="short">w</span> <span class="short">w</span><span class="short">o</span><span class="short">r</span><span>l</span><span>d</span>
span {
color: white;
display: inline-block;
position: relative;
height: 1em;
}
span:before {
content: '';
position: absolute;
top: .2em;
right: 0;
bottom: .1em;
left: 0;
background-color: black;
z-index: -1;
}
span.short:before {
top: .4em;
}
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