Creating a triangle in css with a gradient background

后端 未结 3 1182
闹比i
闹比i 2021-01-05 13:24

I am trying to create a triangle in css with a gradient background. I have not had any success as yet. Is there way to do this to bring off this effect seen in the image bel

相关标签:
3条回答
  • 2021-01-05 13:44

    Creating triangles (or other shapes - pentagons, hexagons, octagons, decagons, dodecagons, tetradecagons, octadecagons and so on) with a gradient (or any other kind of image background) is really easy with CSS transforms.

    But in this case you don't even need a triangle. You just need to rotate a square pseudo-element by 45deg and apply the gradient on that from corner to corner.

    demo

    <div class='warn'></div>
    

    CSS:

    .warn {
      position: relative;
      margin: 0 auto;
      border: solid 1px darkred;
      width: 12em; height: 3em;
      border-radius: .2em;
      background: linear-gradient(lightcoral, firebrick);
    }
    .warn:before {
      position: absolute;
      top: 50%; left: 0;
      margin: -.35em -.45em;
      border-left: inherit; border-bottom: inherit;
      /* pick width & height such that 
         the diagonal of the square is 1em = 1/3 the height of the warn bubble */
      width: .7em; height: .7em;
      border-radius: 0 0 0 .2em;
      transform: rotate(45deg);
      background: linear-gradient(-45deg, firebrick -100%, lightcoral 200%);
      content: '';
    }
    
    0 讨论(0)
  • 2021-01-05 13:54

    You can create a CSS triangle, but not a CSS triangle that is itself a gradient. The only trick I would suggest is to pick a color that most resembles the color within the gradient background. It just depends on how big your gradient actually is, and how well the triangle will blend in.

    For the red div, you could try using the color #d94040, but then it will lack a border and a drop shadow. However, these can be added. To add a border to a CSS triangle, you can place a inside your that is also a CSS triangle that is the same size. TThis would require using absolute positioning and z-index to overlap them.

    Or you can use ::after or ::before to create your CSS triangles without the added HTML code, but then that would only work in modern browsers only.

    0 讨论(0)
  • 2021-01-05 13:56

    In CSS3, you can create a triangle with the 'border trick'. This border can be colored and can have a background.

    WebKit now (and Chrome 12 at least) supports gradients as border image.

    For a more supported solution i suggest you to 'gradient' the background of a :before pseudo element for witch you would apply a 'background-gradient' + the ( css triangle with border ) trick.

    Here is a cssTriangle generator for you to experiment.

    0 讨论(0)
提交回复
热议问题