带边框的CSS三角形

时间:2014-01-29 13:41:09

标签: css css3

我已经制作了一个css三角形:

width: 0; 
height: 0; 
border-top: 10px solid transparent;
border-bottom: 10px solid transparent; 
border-right:10px solid blue;

如何为三角形添加边框?

1 个答案:

答案 0 :(得分:2)

最简单的方法是将2个元素(标记+标记或标记+标记:伪元素)宽度相对/绝对定位(使用边框大小)叠加为链接中的xplained:CSS triangle custom border color

但是如果你想要一个三角形大小,包含文字或图像,半透明或背景,你可以使用CSS3变换和2个元素:demo http://codepen.io/gc-nomade/pen/gdoGA

CSS

.triangle {
  display:inline-block;
  margin: 0 1em;
  padding-top:5px;/* room for box-shadow eventually */
  width:10em;
  border-bottom:2px solid;/* bottom border of triangle */
  overflow:hidden;/* hide part of span */
  position:relative; /* trigger it to be reference for absolute childs */
  text-align:center;
  color:turquoise; /* it gives as well  border and shadow color if not define else where */
  text-shadow: 1px 1px 1px black, -1px -1px 1px white;
  box-shadow:0 4px 5px -5px black; /* we can give a reduced shadow */
}
/* now, set an height to triangle and center text */
.triangle p {
  margin:0;
  display:inline-block;/* inline-boxe can vertical-align aide another one */
  max-width:50%; /* try to keep it inside drawn triangle */
  padding-bottom:5%; /* get it not too close to bottom */
}
.triangle:before {
  content:'';
  display:inline-block;/* to set aside text */
  padding-top:50%; /* gives a triangle shape to div with height equal to minimum halh of width */
  vertical-align:bottom;/* make sure text is layed from bottom */
}
.triangle .notext {/* this will draw the 2 other edges of triangle */
  width:100%;
  background:linear-gradient(to bottom right,pink 5%,yellow 15% ,purple 30%);
  padding-top:100%;/* here we want a square or a container high enough */
  position:absolute; /* off the flow to disturb nothing */
  z-index:-1; /* don 'hide other content */
  border:2px solid; /* borders ! */
  left:0;
  transform:rotate(45deg); /* turn it a bit */
  transform-origin: 24.5% 59.5% ; /* control point of rotation */
  box-shadow:0 0 5px black; /* yes we can */
}
/* check if any size is fine */
.triangle + .triangle {
  width:15em;
}
.triangle + .triangle + .triangle {
  width:8em;
}
div#auto.triangle {width:auto;}
body {
  background:repeating-linear-gradient(to left, gray, purple,lime,violet,turquoise,orange,white 5em);
  text-align:center;
}

HTML基础:

<div class="triangle"> 
  <p>SOME TEXTE</p> 
  <span class="notext"></span>
</div>

要调整三角形的形状或旋转,可以更改div的border-xx,使用padding-top(div / span),transform-origin和transform:rotate(xxdeg)&amp;最终是跨度的宽度。