边框上的CSS渐变

时间:2015-05-25 18:03:37

标签: html css background border gradient

在以下代码中,渐变的宽度为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" />

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

1 个答案:

答案 0 :(得分:1)

这是因为默认情况下背景将延伸到边框边缘。您可以通过设置background-clip: padding-box;来使用background-clip属性来避免这种情况。

工作示例:

&#13;
&#13;
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;
}
&#13;
<input type="text" id="demo" />
<input type="text" />
&#13;
&#13;
&#13;