【问题标题】:Div with top left and right corner same color with linear gradient具有线性渐变的左上角和右上角相同颜色的 Div
【发布时间】:2016-03-07 10:11:59
【问题描述】:

我想通过 CSS 获得以下 UI。我尝试使用以下方法,但它没有产生我预期的输出。

background: linear-gradient(to bottom right, black 20%, white 20%); 

黑色边框不是必需的。它们仅用于边界

任何人都可以提供任何建议或解决方案来解决这个问题吗?

【问题讨论】:

  • @vucko,我尝试了背景:线性渐变(右下角,黑色 20%,白色 20%);我可以举一些与此相关的例子吗?我是新手。
  • 是否也需要黑色边框(或)它们出现在图像中仅用于标记边界?
  • 不需要黑色边框。它们只是为了边界。

标签: css css-shapes linear-gradients


【解决方案1】:

这也可以使用一对linear-gradient 背景图像来实现。我们所要做的就是创建具有所需大小的渐变并将它们放置在元素的左上角和右上角。

线性渐变产生的输出是响应式的,一个优点是它不需要任何额外的伪元素(因此它们可以用于其他目的)。主要缺点是浏览器对渐变的支持。它们适用于所有现代浏览器,但不适用于 IE9-。另一个问题是,众所周知,随着容器的尺寸变大,渐变会产生锯齿状边缘,但只要 不需要边框,这不会是一个大问题。

div {
  position: relative;
  height: 200px;
  width: 175px;
  background-color: rgb(34, 177, 76);
  background-image: linear-gradient(to top left, transparent calc(50% - 1px), rgb(0, 162, 232) calc(50% + 1px)), linear-gradient(to top right, transparent calc(50% - 1px), rgb(0, 162, 232) calc(50% + 1px));
  background-size: 30% 85%;
  background-position: left top, right top;
  background-repeat: no-repeat;
  transition: all 2s;  /* just for demo */
}

div:hover {
  height: 400px;
  width: 350px;
}
<div></div>

如果需要,我们还可以通过更多地使用渐变来添加边框。

div {
  position: relative;
  height: 200px;
  width: 175px;
  background-color: rgb(34, 177, 76);
  background-image: linear-gradient(to top left, transparent calc(50% - 1px), black 50%, black calc(50% + 1px), rgb(0, 162, 232) calc(50% + 2px)), linear-gradient(to top right, transparent calc(50% - 1px), black 50%, black calc(50% + 1px), rgb(0, 162, 232) calc(50% + 2px));
  background-size: 30% 85%;
  background-position: left top, right top;
  background-repeat: no-repeat;
  transition: all 2s;
  /* just for demo */
  border: 2px solid black;
}
div:hover {
  height: 400px;
  width: 350px;
}
<div></div>

【讨论】:

  • 此代码是否支持所有浏览器/版本?如果有任何问题,请告诉我。
  • @getty:它不仅在 IE9、IE8 中有效(因为它们不支持渐变)。应该可以在所有其他浏览器中运行,尽管某些旧版本的 Chrome,Firefox 需要 -webkit--moz- 前缀。可以找到浏览器支持图here
  • 更喜欢您的解决方案 :)
【解决方案2】:

一种方法是使用::before::after 伪元素:

#foo{
  position: relative;
  height: 200px;
  width: 200px;
  background-color: green;
}

#foo::before, #foo::after{
  content: '';
  position: absolute;
  top: 0;
  width: 0;
  height: 0;
  border-style: solid;
}

#foo::before{
  left: 0;
  border-width: 200px 70px 0 0;
  border-color: #007bff transparent transparent transparent;
}

#foo::after{
  right: 0;
  border-width: 0 70px 200px 0;
  border-color: transparent #007bff transparent transparent;
}
<div id="foo"></div>

JSFiddle

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-17
    • 2019-07-03
    • 2020-06-19
    • 1970-01-01
    • 2021-10-30
    • 2014-12-16
    • 1970-01-01
    相关资源
    最近更新 更多