How do I make a CSS triangle with smooth edges?

2019-01-21 22:14发布

I have a triangle (JSFiddle) using this CSS:

.triangle {
    width: 0;
    height: 0;
    border-top: 0;
    border-bottom: 30px solid #666699;
    border-left: 20px solid transparent; 
    border-right: 20px solid transparent;
    }

And this HTML:

<div class="triangle"></div>

This makes a triangle, but the diagonal lines are jagged and pixelated. How can I make them smooth? (I was able to smooth them out in Safari and Chrome by making them dotted, but that broke the triangles in Firefox and IE.)

8条回答
你好瞎i
2楼-- · 2019-01-21 23:08

Using border style inset for transparent borders gives much better results in Firefox:

border-top: 22px solid $pink;
border-right: 84px inset transparent;
border-left: 84px inset transparent;
查看更多
小情绪 Triste *
3楼-- · 2019-01-21 23:12

What really helped me when first stumbling over this was to scale a uniform triangle by a certain amount. Firefox seems to be particularly 'edgy' with scalene triangles. Interesting though, perfect triangles get rendered without jagged edges. If CSS transforms are possible in your project, just try:

.triangle {
  width: 0;
  height: 0;
  border-top: 0;
  border-bottom: 20px solid #666699;
  border-left: 20px solid transparent; 
  border-right: 20px solid transparent;
  -moz-transform: scaleY(1.5); // optional: replace with Sass/SCSS/LESS mixin
  -moz-transform-origin: top; // optional: replace with mixin, too
}

This fixed the aliasing across the edge for me. JSFiddle here (Mozilla only right now). Hope this helps!

查看更多
登录 后发表回答