Wednesday 6 February 2019

html - How can I style a part of a single character with overlays using a dynamic width?




Question



Can I style just a part of a single character?



Meaning



CSS attributes cannot be assigned to parts of characters. But if you want to style only a certain section of a character, there is no standardized way to do that.



Example




Is it possible to style an "X" which is half-way red and then black?



Expected result



Not working code




X




.content {
position: relative;
font-size: 50px;
color: black;
}

.content:after {
content: 'X';
color: red;

width: 50%;
position: absolute;
overflow: hidden;
}


Demo on jsFiddle



Purpose




My intention is styling the Font Awesome icon-star symbol. If I have an overlay with dynamic width, shouldn't it be possible to create an exact visualization of scores?


Answer



While playing around with a demo fiddle, i figured it out myself and wanted to share my solution. It's quite simple.



First things first: The DEMO



To partly style a single character, you need extra markup for your content. Basically, you need to duplicate it:



<​div class="content"> 
X

X



Using pseudo-elements like :after or :before would be nicer, but i didn't found a way to do that.



The overlay needs to be positioned absolutely to the content element:



​.content {
display: inline-block;

position: relative;
color: black;
}

​.overlay {
width: 50%;
position: absolute;
color: red;
overflow: hidden;
}​



Do not forget overflow: hidden; in order to cut off the remaing part of the "X".



You can use any width instead of 50% which makes this approach very flexible. You can even use a custom height, other CSS attributes or a combination of multiple attributes.




No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...