Search code examples
cssfontscolors

Two-tone font coloring in CSS?


I really like the look of two-tone buttons and fonts. I am thinking of when the top half of the font is one color and the bottom half is a variation on the same color. For an example see most of the buttons on an iPhone or the logo here http://ming.ly.

mingly

Is it possible to recreate this effect in CSS?


Solution

  • I managed to achieve that with CSS...

    Example

    Example

    CSS

    div {
        position: relative;  
        color: #0f0;
        font-size: 28px;
    }
    
    div span {
        height: 50%;
        position: absolute;
        color: #f00;
        overflow: hidden;  
    }
    

    HTML

    <div>
        <span>Hello</span>
        Hello
    </div>
    

    jsFiddle.

    Tested in Firefox 5.

    Keep in mind that it is not very semantic to repeat the text to be displayed once.

    Depending on the browsers you need to support, you could ditch that inner span for something like this in the CSS...

    div:before {
        content: "Hello";
        height: 50%;
        position: absolute;
        color: #f00;
        overflow: hidden;   
    }
    

    jsFiddle.

    As far as I know, there is no value for content which will automatically use that element's text node. You could put it on the title attribute and use attr(title) (or any other attribute).

    You could also use JavaScript to do the repeating.

    var textRepeat = document.createElement('span'),
        textRepeatTextNode = document.createTextNode(element.firstChild.data);
    
    element.appendChild(textRepeat.appendChild(textRepeatNode));
    

    If the first child was not necessarily a text node, you could use element.textContent || element.innerText.