I’m a German teacher in primary school. I want beginning readers to read some text on my practice website. To help them I need the syllables to alternate colours (black / grey, as shown in the image). Due to the amount of text I cannot colour them by hand. Luckily there is CSS hyphenation support. Is there any way I can use this to achieve colouration?
We will only use Chrome (though I’m happy to have a more universal approach). I don’t know a lot about coding so I would appreciate a working example that I can plug into my site, if possible. Thank you very much!
So far I only have this (not trying to solve the issue yet):
#word-display {
font-size: 40px;
margin: 20px;
padding: 10px;
font-family: 'NordDruck', 'AndikaW', sans-serif; /* Fallback to sans-serif if AndikaW is not available */
}
2
Answers
You can use span
Example:
html and css
In this example defg and jkl will have a blue text Color.
Additionally you can give span a class name and have different Color for different letters or words.
Note: this code works OK for me on Firefox Windows10. It does not work properly on Edge/Chrome as they don’t consider a word with spans in it to be a word for hyphenation purposes.
As a workaround you could perhaps create the spanned text using Firefox then copy it (using e.g. devtools) into your HTML so it can be seen in Chrome.
…………………………………………………………………….
To color bits of text differently they need to be within some element such as a span.
To find where to set these spans, this snippet first puts each character into its own span and then the text into a very narrow div so the browser breaks the words up with its hyphenation algorithm.
This means each syllable (OP confirmed that the browser hyphenation should be good enough to indicate syllables) will start a new line.
We can then find all those characters that start a newline (are on the left) and put the end and start of spans there (
</span><span>
).The div is then given the full width of its parent and the text with these spans added.
Coloring of every even and every odd span is set in the stylesheet.
(Note all other styling during the calculations is deliberately put inline using JS to make the code more self-contained and portable).
Here’s an example with Snow White (I hope it’s OK, my German isn’t good enough to check) from https://www.sloeful.com/german/fairytales/snow-white%5D%5B1%5D
Here’s what I see on Firefox: