CSS 边框渐变

CSS gradient on border

在下面的代码中,渐变的宽度为 100%,并越过左侧的边框。

JSFiddle

input {
    background: transparent;
    font-family:'Open Sans';
    border: 1px solid rgba(255, 255, 255, 0.2);
    box-sizing: border-box;
    padding: 5px;
    color: rgb(164, 164, 164);
}
input:focus {
    outline: none;
    border: 1px solid rgba(255, 255, 255, 0.5)
}
#demo {
    background : transparent linear-gradient(to right, rgba(109, 179, 242, 0) 0%, rgb(24, 189, 70) 100%, rgba(54, 144, 240, 0) 0%, rgba(58, 107, 182, 0) 100%);
}
body {
    background: hsla(0, 5%, 5%, 1) linear-gradient(to right top, rgba(10%, 0%, 0%, 1), rgba(0%, 0%, 0%, 1)) no-repeat fixed;
}
<input type="text" id="demo" />
<input type="text" />

为什么会发生这种情况,我该如何避免这种情况?

那是因为背景默认会延伸到边框边缘。您可以通过设置 background-clip: padding-box;.

使用 background-clip 属性 来避免这种情况

工作示例:

input {
    background: transparent;
    font-family:'Open Sans';
    border: 1px solid rgba(255, 255, 255, 0.2);
    box-sizing: border-box;
    padding: 5px;
    color: rgb(164, 164, 164);
}
input:focus {
    outline: none;
    border: 1px solid rgba(255, 255, 255, 0.5)
}
#demo {
    background : transparent linear-gradient(to right, rgba(109, 179, 242, 0) 0%, rgb(24, 189, 70) 100%, rgba(54, 144, 240, 0) 0%, rgba(58, 107, 182, 0) 100%);
    background-clip: padding-box;
}
body {
    background: hsla(0, 5%, 5%, 1) linear-gradient(to right top, rgba(10%, 0%, 0%, 1), rgba(0%, 0%, 0%, 1)) no-repeat fixed;
}
<input type="text" id="demo" />
<input type="text" />