我能够提供背景图像的起始位置。但是,如果我为纯色填充背景提供位置,它不起作用。这是js fiddle的链接。
那么我们可以设置实心填充背景的起始位置和大小吗?
谢谢!
我能够提供背景图像的起始位置。但是,如果我为纯色填充背景提供位置,它不起作用。这是js fiddle的链接。
那么我们可以设置实心填充背景的起始位置和大小吗?
谢谢!
我会采用与StuR类似的方法,但使用背景位置而不是渐变点。然后您可以像通常设置背景位置一样进行操作。
div {
background:linear-gradient(left, #000, #000) no-repeat 50px 50px;
}
to left
代替left
。如果不加 -webkit
前缀,我的Chrome(79)会抛出错误。请注意,翻译时保持原文意思不变,让内容更通俗易懂。 - sofly这是一种用线性渐变和透明颜色来偏移实心背景色的方法,可以在前x个像素中使用:
.offset {
background-image: linear-gradient(left, transparent 300px,rgba(39,39,39,.5) 300px, rgba(39,39,39,.5) 100%);
width: 100%;
height: 500px;
}
这里有一个在JSFiddle上的演示。
你无法对背景色进行偏移。只有背景图像才有位置。
如果你可以创建一个具有背景颜色、高度和宽度的 ::before 伪元素,然后将其偏移相对于其父元素,那么你就可以完全控制其外观。这比在伪元素中添加边框要容易得多:
/* adding a ::before element with bg and border radius to create a
cropped circle to overlay parent bg image's blue right end */
.myElement::before {
background-color: #fff;
content: "";
margin: 0 auto;
position: absolute;
top: 43px;
right: 0;
width: 300px;
height: 201px;
z-index: -1;
border-top-right-radius: 8px;
border-bottom-right-radius: 8px;
}
:before
伪元素需要在 myElement
的内容后面,确保将 position: relevant
指定给 myElement
。 - Wtower使用 linear-gradient
时,请注意不要出现不正确的对齐。
以下是更好的做法:
background: linear-gradient(#6699cc, #6699cc);
background-size: auto 4em;
background-repeat: no-repeat;
linear-gradient
仅用于生成纯色,然后调整大小以反映覆盖区域的大小。background-position
,例如:background: linear-gradient(#6699cc, #6699cc);
background-size: calc(100% - 30px) auto;
background-repeat: no-repeat;
background-position: right;
https://developer.mozilla.org/en-US/docs/Web/CSS/gradient/linear-gradient
https://developer.mozilla.org/en-US/docs/Web/CSS/background-size
https://developer.mozilla.org/en-US/docs/Web/CSS/calc
https://developer.mozilla.org/en-US/docs/Web/CSS/background-repeat
https://developer.mozilla.org/en-US/docs/Web/CSS/background-position
是的,使用线性渐变可以实现:
div { background-image: linear-gradient(transparent 10px, grey 10px); }
linear-gradient(to right, blue 10px, transparent 10px)
表示水平方向的渐变。 - Aidinbackground-size
代替background-position
来限制有颜色的区域:
// randomly set background size every 1 second
var elm = document.querySelector('div');
window.setInterval(()=> {
var randomValue = Math.random()*100;
elm.style.backgroundSize = randomValue + '%';
}, 1000)
div {
height: 100px;
border: 1px solid black;
transition: .4s ease-out;
background: linear-gradient(to right, black, black) no-repeat;
background-size: 0; /* <--- starting from 0% */
}
<div></div>
div {
::before {
border-top: 10px solid #0066a4;
content:"";
margin: 0 auto; /* this centers the line to the full width specified */
position: absolute; /* positioning must be absolute here, and relative positioning must be applied to the parent */
top: 12px; left: 0; right: 0; bottom: 0;
z-index: -1;
}
}
请查看Eric Rasch的CodePen,以获得一个工作示例:https://codepen.io/ericrasch/pen/Irlpm