CSS更精简的渐变效果

时间:2016-04-26 11:29:41

标签: css linear-gradients

我希望在我的div边界中获得以下两种风格: 1.如果div的高度是X. 我想要4px从顶部开始一些渐变颜色。 3.我想从底部开始4px开始一些渐变色。(相同颜色) 所以它看起来像这样: | 4px透明 |从白色到黑色渐变 | |在这里结束黑色 |从黑色到白色渐变(另一个方向) | | |在这里结束白色 | 4px transparet

2 个答案:

答案 0 :(得分:2)

您需要做的就是创建渐变并将其分配给border-image属性。这是well supported in modern browsers,除非您希望支持IE10,否则可以使用。

div {
  height: 100px;
  width: 200px;
  border-style: solid;
  border-width:0px 4px;
  border-image: linear-gradient(to bottom, transparent 4px, red 4px, orange 50%, red calc(100% - 4px), transparent calc(100% - 4px));
  border-image-slice: 1;
  border-image-repeat: stretch;
  background: beige;
}
<div>Some div</div>

以下是解释上述代码段中使用的linear-gradient的方法:

linear-gradient(to bottom, /* the direction of the gradient */
                transparent 4px, /* make it transparent till 4px from start */
                red 4px, /* start with the required color exactly at 4px */
                orange 50%, /* make it change from red to orange at 50% - half distance */
                red calc(100% - 4px), /* change it back from orange to red at 4px before 100% */
                transparent calc(100% - 4px) /* leave the last 4px as transparent again */
                );

答案 1 :(得分:1)

你可以通过一些造型技巧来实现这个目标

首先,我们使用定位的伪元素(左/右,因为你指出高度作为决定因素)而不是边界。

我们使用4px顶部和底部填充来创建透明部分(和背景剪辑,因此渐变背景不会延伸到填充中)。

然后它是一个简单的线性渐变。

*,
::before,
::after {
  box-sizing: border-box;
}
body {
  background: pink;
}
div {
  height: 90vh;
  width: 60%;
  margin: 5vh auto;
  background: #c0ffee;
  position: relative;
}
div::before,
div::after {
  content: '';
  position: absolute;
  top: 0;
  height: 100%;
  padding: 4px 0;
  width: 2px;
  background-clip: content-box;
  background-image: linear-gradient(to bottom, white, black 50%, white);
}
div::before {
  left: -2px;
}
div::after {
  right: -2px;
}
<div>
</div>

使用calc更复杂的渐变而没有额外的剪裁/填充

div::before,
div::after {
  content: '';
  position: absolute;
  top: 0;
  height: 100%;
  width: 2px;
  background-clip: content-box;
  background-image: linear-gradient(to bottom, 
    transparent,
    transparent 4px,
    white 4px, 
    black 50%, 
    white calc(100% - 4px),
    transparent calc(100% - 4px),
    transparent);
}

*,
::before,
::after {
  box-sizing: border-box;
}
body {
  background: pink;
}
div {
  height: 90vh;
  width: 60%;
  margin: 5vh auto;
  background: #c0ffee;
  position: relative;
}
div::before,
div::after {
  content: '';
  position: absolute;
  top: 0;
  height: 100%;
  width: 2px;
  background-clip: content-box;
  background-image: linear-gradient(to bottom, 
    transparent,
    transparent 4px,
    white 4px, 
    black 50%, 
    white calc(100% - 4px),
    transparent calc(100% - 4px),
    transparent);
}}
div::before {
  left: -2px;
}
div::after {
  right: -2px;
}
<div>
</div>

相关问题