CSS技巧-CSS的形状有很多不同的CSS形状,我特别困惑于三角形:
#三角形向上{宽度:0;高度:0;左边框:50px实心透明;右边框:50px实心透明;边框底部:100px纯红色;}<div id=“triangle up”></div>
它是如何以及为什么工作的?
CSS技巧-CSS的形状有很多不同的CSS形状,我特别困惑于三角形:
#三角形向上{宽度:0;高度:0;左边框:50px实心透明;右边框:50px实心透明;边框底部:100px纯红色;}<div id=“triangle up”></div>
它是如何以及为什么工作的?
当前回答
剪辑路径对我来说效果最好-适用于具有和不具有固定尺寸的div/容器:
.triangleContainer{
position: relative;
width: 500px;
height: 500px;
}
.triangleContainer::before{
content: "";
position: absolute;
background:blue;
top: 0;
left: 0;
width: 100%;
height: 100%;
clip-path: polygon(50% 0, 0 100%, 100% 100%);
}
其他回答
其他人已经很好地解释了这一点。让我给你一个动画,它将快速解释这一点:http://codepen.io/chriscoyier/pen/lotjh
这里有一些代码供您使用和学习这些概念。
HTML格式:
<html>
<body>
<div id="border-demo">
</div>
</body>
</html>
CSS:
/*border-width is border thickness*/
#border-demo {
background: gray;
border-color: yellow blue red green;/*top right bottom left*/
border-style: solid;
border-width: 25px 25px 25px 25px;/*top right bottom left*/
height: 50px;
width: 50px;
}
玩这个,看看会发生什么。将高度和宽度设置为零。然后移除顶部边框并使左右透明,或者只需查看下面的代码以创建css三角形:
#border-demo {
border-left: 50px solid transparent;
border-right: 50px solid transparent;
border-bottom: 100px solid blue;
}
SASS(SCSS)三角形混合
我写这篇文章是为了让自动生成CSS三角形变得更容易(也更干燥):
// Triangle helper mixin (by Yair Even-Or)
// @param {Direction} $direction - either `top`, `right`, `bottom` or `left`
// @param {Color} $color [currentcolor] - Triangle color
// @param {Length} $size [1em] - Triangle size
@mixin triangle($direction, $color: currentcolor, $size: 1em) {
$size: $size/2;
$transparent: rgba($color, 0);
$opposite: (top:bottom, right:left, left:right, bottom:top);
content: '';
display: inline-block;
width: 0;
height: 0;
border: $size solid $transparent;
border-#{map-get($opposite, $direction)}-color: $color;
margin-#{$direction}: -$size;
}
用例示例:
span {
@include triangle(bottom, red, 10px);
}
游乐场页面
重要提示:如果三角形在某些浏览器中显示为像素化,请尝试此处描述的方法之一。
这是一个老问题,但我认为值得分享如何使用这种三角形技术创建箭头。
步骤1:
让我们创建两个三角形,对于第二个,我们将使用:after伪类,并将其放置在另一个的正下方:
.箭头{宽度:0;高度:0;边框半径:50px;显示:内联块;位置:相对;}.arrow:在之后{内容:“”;宽度:0;高度:0;位置:绝对;}.向上箭头{左边框:50px实心透明;右边框:50px实心透明;边框底部:50px实心#333;}.向上箭头:之后{顶部:5px;左边框:50px实心透明;右边框:50px实心透明;边框底部:50px实心#ccc;右:-50px;}<div class=“arrow arrow up”></div>
步骤2
现在,我们只需将第二个三角形的主要边界颜色设置为与背景相同的颜色:
.箭头{宽度:0;高度:0;边框半径:50px;显示:内联块;位置:相对;}.arrow:在之后{内容:“”;宽度:0;高度:0;位置:绝对;}.向上箭头{左边框:50px实心透明;右边框:50px实心透明;边框底部:50px实心#333;}.向上箭头:之后{顶部:5px;左边框:50px实心透明;右边框:50px实心透明;边框底部:50px实心#fff;右:-50px;}<div class=“arrow arrow up”></div>
摆弄所有箭头:http://jsfiddle.net/tomsarduy/r0zksgeu/
我知道这是一个旧的方法,但我想在讨论中补充一点,单独使用HTML和CSS创建三角形至少有5种不同的方法。
使用边框使用线性梯度使用圆锥梯度使用转换和溢出使用剪辑路径
我认为,除了方法3(使用圆锥曲线梯度)之外,这里已经介绍了所有内容,所以我将在这里分享:
.三角形{宽度:40px;高度:40px;背景:圆锥形梯度(50%50%,透明135度,绿色0,绿色225度,透明0);}<div class=“triangle”></div>
现在完全不同了。。。
不要忘记像html实体这样简单的解决方案,而不要使用css技巧:
▲
结果:
▲
请参见:上下三角形的HTML实体是什么?