Gradient text cross browser

518 views Asked by At

I'm trying to make a menu bar with a horizontal gradient. I've had some success using -webkit-background-clip but that won't work in Firefox.

I found a jQuery plugin pxgradient that's cross browser compatible but I can't get it to span the gradient over several li elements. See the following jsfiddle:

http://jsfiddle.net/vnv4nyhj/10/

function gradient1() {
    $(".test").pxgradient({
        step: 10,
        colors: ["#ff0066", "#2850FF"],
        dir: "x"
    });
};

I want the gradient to be more like the top one. Ideally I'd like the border-bottom to include the same gradient on hover but I can possibly live in a world without that.

PS- the font-awesome icon is there only because it gave me problems earlier so I included now to make sure it works.

Update: Another possible idea I was playing with was to read the number of elements, then divide the colours per element and use the nth-child() selector to assign each color.

<script>
//Get number of list items
var menuItems = $("li").children().length;

//Convert colors to hex
hexString1 = '2850FF';
hexString2 = 'FF0066';
color1 = parseInt(hexString1, 16);
color2 = parseInt(hexString2, 16);

//Calculate difference in colors and color step
colorDifference = color2 - color1;
colorStep = colorDifference / (menuItems - 1);
colorStep = parseInt(colorStep);

//Loop through elements and apply gradients
for (i = 0; i < menuItems; i++) {
    newColor1 = color1 + (i * colorStep);
    newColor2 = color1 color2 -1;
    gradientStart = newColor1.toString(16);
    gradientEnd = newColor2.toString(16);

    //use gradientStart and gradientEnd as colors in the function, not sure on this part yet

}

</script>

It's seems so overkill though, there must be a simpler solution? Also an element with many characters will have a relatively slow gradient compared to one with a few characters. That could possibly be fixed by counting the numbers of characters per element, but it just all seems rather inefficient.

1

There are 1 answers

1
vals On BEST ANSWER

An easy solution, that will work in FF, Chrome, and Safari, using blend modes.

The trick is that the gradient is set under the a, in the ul .

Setting mix-blend-mode: screen, this colors will show only on the black places (the text, and the border when hovered)

ul {
    display: inline-block;
    padding: 0;
    font-size: 30px;
    font-weight: bolder;
    background: linear-gradient(90deg, red, blue);
}
li {
    mix-blend-mode: screen;
    background-color: white;  
    box-shadow: 8px 0px 0px white;
}
li, li a {
    display: inline-block;
    text-decoration: none;
    border-bottom: 3px solid white;
}
li:hover a {
    border-bottom: 3px solid black;
    text-shadow: 0px 0px 2px gray;
}
<div class="navigation">
 <ul>
  <li><a href="#">Nav 1</a></li>
  <li><a href="#">Nav 2</a></li>
  <li><a href="#">Nav 3</a></li>
  <li><a href="#">Nav 4</a></li>
  <li><a href="#">Nav 5</a></li>
 </ul>
</div>