我想用CSS创建一个像这里展示的上下箭头,但与其实心填充颜色不同,我想设置内部为白色,只有三角形周围有边框(即三角形将是多色的,内部有一种颜色,边框有另外一种颜色)。
这是否可行,如果可以,应该如何实现?
要使用CSS创建三角形,我们使用一个边框为零宽度/高度的元素:
.arrow-up {
width : 0;
height : 0;
border-left : 50px solid transparent;
border-right : 50px solid transparent;
border-bottom : 50px solid black;
}
因为我们使用边框来创建箭头,所以不能仅给它一个边框,但是我们可以将一只箭头覆盖在稍微大一点的箭头上,以呈现出边框的外观:
HTML --
<div class="top"></div>
<div class="bottom"></div>
CSS --
(CSS -).top {
position : absolute;
top : 6px;
left : 10px;
width : 0;
height : 0;
z-index : 100;
border-left : 50px solid transparent;
border-right : 50px solid transparent;
border-bottom : 50px solid black;
}
.bottom {
position : absolute;
width : 0;
height : 0;
z-index : 99;
border-left : 60px solid transparent;
border-right : 60px solid transparent;
border-bottom : 60px solid red;
}
这里有一个演示:http://jsfiddle.net/jasper/qnmpb/1/
然后您可以将两个三角形的 DIV 元素放入容器中,并根据需要移动该容器:
HTML --
<div id="container">
<div class="top"></div>
<div class="bottom"></div>
</div>
CSS --
#container {
position : relative;
top : 25px;
left : 25px;
}
这里有一个演示:http://jsfiddle.net/jasper/qnmpb/3/
我回到了这个答案,并注意到创建双三角形并不需要单独的HTML元素。您可以使用伪元素,:before
和:after
。例如,将 .top
选择器替换为类似.my-element-that-needs-a-triangle:before
,将 .bottom
选择器替换为类似.my-element-that-needs-a-triangle:after
。
:before
和:after
。.arrow-dropdown
添加了display:inline-block;
,以便能够创建具有投影的下拉菜单。它后面是一个带有红色边框的基本三角形.arrow-only
。
body {
margin: 10px;
background: #1670c4;
}
.text {
display: inline-block;
font-size: 15px;
color: #fff;
text-shadow: 1px 1px 2px rgba(0,0,0,0.4);
cursor: default;
}
.arrow-dropdown {
display: inline-block;
position: relative;
vertical-align: middle;
margin: 1px 0 0 8px;
width: 8px;
height: 7px;
}
.arrow-dropdown:after {
content: '';
position: absolute;
border-style: solid;
border-width: 7px 4px 0;
border-color: #fff transparent transparent transparent;
display: block;
width: 0;
z-index: 1;
}
.arrow-dropdown:before {
content: '';
position: absolute;
border-style: solid;
border-width: 8px 5px 0;
border-color: rgba(0,0,0,0.3) transparent transparent transparent;
display: block;
width: 0;
z-index: 0;
}
.arrow-only {
position: relative;
vertical-align: middle;
margin: 10px 0 0 8px;
width: 8px;
height: 7px;
}
.arrow-only:after {
content: '';
position: absolute;
border-style: solid;
border-width: 12px 9px 0;
border-color: #fff transparent transparent transparent;
display: block;
width: 0;
z-index: 1;
}
.arrow-only:before {
content: '';
position: absolute;
border-style: solid;
border-width: 15px 11px 0;
border-color: #f00 transparent transparent transparent;
display: block;
width: 0;
z-index: 0;
margin:-1px 0 0 -2px;
}
<div class="text">
Dropdown text
</div><div class="arrow-dropdown"></div>
<div class="arrow-only"></div>
根据您的使用方式,您可以使用CSS transform: rotate()
创建一个带边框和盒子阴影的三角形,而无需使用三角形边框hack。请参见我的答案:https://dev59.com/Emox5IYBdhLWcg3w9o6h#8867645