
We'll do it using just css pseudo selectors!
This technique will work with dynamically generated content and different font sizes and widths.
HTML:
<div class='split-color'>Two is better than one.</div> CSS:
.split-color > span { white-space: pre-line; position: relative; color: #409FBF; } .split-color > span:before { content: attr(data-content); pointer-events: none; /* Prevents events from targeting pseudo-element */ position: absolute; overflow: hidden; color: #264A73; width: 50%; z-index: 1; } To wrap the dynamically generated string, you could use a function like this:
// Wrap each letter in a span tag and return an HTML string // that can be used to replace the original text function wrapString(str) { var output = []; str.split('').forEach(function(letter) { var wrapper = document.createElement('span'); wrapper.dataset.content = wrapper.innerHTML = letter; output.push(wrapper.outerHTML); }); return output.join(''); } // Replace the original text with the split-color text window.onload = function() { var el = document.querySelector('.split-color'), txt = el.innerHTML; el.innerHTML = wrapString(txt); }