Search code examples
htmlcsslinear-gradients

Weird effect when applying transparent border over an element with a gradient background


When applying a transparent border over an element with a linear-gradient as the background, I get a weird effect.

enter image description here

Notice the left and right sides of the element don't have the proper colours (they're some way switched) and are weirdly flat.

HTML

<div class="colors">
</div>

CSS

.colors {
    width: 100px;
    border: 10px solid rgba(0,0,0,0.2);
    height: 50px;
    background: linear-gradient(to right, 
        #78C5D6,
        #459BA8,
        #79C267,
        #C5D647,
        #F5D63D,
        #F08B33,
        #E868A2,
        #BE61A5);
}

Why is this showing a weird effect on the left and right side of the element, and What can I do about it?

Here is the fiddle: http://jsfiddle.net/fzndodgx/3/


Solution

  • That's because the starting and ending points of the gradient are at the edges of the padding-box and border is rendered outside the padding-box. So, the borders look funny because the background is repeated on each side outside the padding-box to cover the border-box.

    The box-shadow:inset is rendered inside the padding-box (just like background) and gives visually the same effect as a border, so you could try using that in place of border:

    box-shadow: inset 0 0 0 10px rgba(0,0,0,0.2);
    padding: 10px;
    

    Because a box-shadow doesn't take up any space, you need to increase your padding accordingly.

    Illustration of padding-box and border-box: enter image description here

    Demo http://jsfiddle.net/ilpo/fzndodgx/5/