2013-03-15 77 views
6

我正尝试在css中用渐变背景创建三角形。我还没有取得任何成功。有没有办法做到这一点,以发挥在下面的图片中看到这种效果。 (附加到了错误的密码错误框中的三角形。)在Photoshop enter image description here用渐变背景在css中创建三角形

设计是设计我在HTML和CSS至今。

enter image description here

这里是CSS我对此刻的三角形。

.error-triangle { 
    wwidth: 0; 
    height: 0; 
    border-top: 10px solid transparent; 
    border-bottom: 10px solid transparent; 
    border-right: 10px solid blue; 
    margin-top: 64px; 
    margin-left: 350px; 
    position: fixed; 
    -webkit-box-shadow: 0 0 3px rgba(102,65,65,.25), 2px 3px 5px rgba(70,34,34,.25), inset 1px 2px rgba(255,255,255,.25); 
     -moz-box-shadow: 0 0 3px rgba(102,65,65,.25), 2px 3px 5px rgba(70,34,34,.25), inset 1px 2px rgba(255,255,255,.25); 
      box-shadow: 0 0 3px rgba(102,65,65,.25), 2px 3px 5px rgba(70,34,34,.25), inset 1px 2px rgba(255,255,255,.25); 
    background-image: -webkit-linear-gradient(bottom, #eb6767, #d94040 35%, #eb6767); 
    background-image: -moz-linear-gradient(bottom, #eb6767, #d94040 35%, #eb6767); 
    background-image:  -o-linear-gradient(bottom, #eb6767, #d94040 35%, #eb6767); 
    background-image:  -ms-linear-gradient(bottom, #eb6767, #d94040 35%, #eb6767); 
    background-image:   linear-gradient(to top, #eb6767, #d94040 35%, #eb6767); 
} 

我就是用这个tutorial on CSS tricks.

+0

CSS只箭:http://cssarrowplease.com/ – Luca 2013-03-15 17:08:50

回答

17

创建三角形(或其他形状 - pentagons, hexagons,八角形,decagonsdodecagonstetradecagonsoctadecagons等)用梯度(或任何其他类型的图像背景)是CSS转换很容易。

但在这种情况下,你甚至不需要一个三角形。你只需要旋转45deg的方形伪元素,并从角落到角落应用渐变。

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

这看起来很棒。你还可以添加文字阴影的代码?谢谢 – MonsterMMORPG 2013-08-16 19:49:05

0

您可以创建一个CSS三角形,而不是CSS三角形本身就是一个梯度。我建议的唯一技巧是挑选最接近渐变背景中颜色的颜色。这取决于你的渐变的实际大小以及三角形的融合程度。

对于红色的div,你可以尝试使用颜色#d94040,但它会缺少边框和阴影。但是,这些可以添加。要为CSS三角形添加边框,您可以在其中放置一个同样尺寸的CSS三角形。这将需要使用绝对定位和z-索引来重叠它们。

或者您可以使用:: after或:: before来创建CSS三角形而不添加HTML代码,但那样只会在现代浏览器中才能使用。

+0

确定。那么,如果我只是使用三角形的图像,那么你认为最好吗? – 2013-03-15 16:21:21

+0

如果是我,我根本不会使用渐变。这会使它看起来不像一个按钮,更像是一个警告。 – Xarcell 2013-03-15 16:24:28

+2

实际上,您可以通过使用变换非常容易地创建具有渐变背景的三角形。 http://codepen.io/thebabydino/pen/cBmxv – Ana 2013-03-15 17:45:14

0

在CSS3中,您可以使用“边框技巧”创建一个三角形。这个边框可以是彩色的,可以有背景。

WebKit现在(和Chrome 12至少)支持渐变作为边框图像。

对于更受支持的解决方案,我建议您将'gradient'背景作为女巫的伪元素,然后应用'background-gradient'+(带边框的css三角形)技巧。

Here is a cssTriangle generator供您试验。