用于创建与箭头主体对齐的箭头的CSS

时间:2014-04-05 02:47:25

标签: css

我需要绘制许多精确定位的水平箭头,指向左,右或两者。我不想使用HTML画布。它将全部用JQuery动态完成,但css参数将与下面大致相同,包括箭头大小和箭头粗细。

这段代码效果很好......

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <style >
        .ArrowHead {
            position: absolute;
            width: 0;
            height: 0;
            border-top: 4px solid transparent;
            border-bottom: 5px solid transparent;
            border-right: 12px solid black;
            top:46px;left:52px;
        }
          .Arrow {
            border-top:solid 1px black;
            position: absolute;
            top:50px;left:50px;
            width:100px;height:1px
        }
    </style>
</head>
<body>
    <div id="Arrow" class="Arrow"></div>
    <div id="ArrowHead" class="ArrowHead"></div>
</body>
</html>

...但是箭头的尖端在箭头的主体上方略微,它只是在箭头的右侧看起来正确对齐,因为箭头的底部大于顶部(更容易看到400%)。然而,很好的幻觉,我希望找出是否有某种方式箭头可以垂直对称,仍然与箭头体完全水平排列。

1 个答案:

答案 0 :(得分:2)

当线条高度为1px时,您将无法垂直居中箭头,因为无法以半像素为单位进行测量。如果你愿意将线宽增加到两个像素,那么很容易。最好将箭头相对于线而不是视口定位(使用相对/绝对定位)。 E.g。

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style>
          .arrow {
            background: black;
            width:100px;
            height:2px;
            position: relative;
        }

        .arrow::before {
            content: "";
            position: absolute;
            width: 0;
            height: 0;
            border-top: 5px solid transparent;
            border-bottom: 5px solid transparent;
            border-right: 12px solid black;
            top:-4px;
            left:-3px;
        }

        .arrow::after {
            content: "";
            position: absolute;
            width: 0;
            height: 0;
            border-top: 5px solid transparent;
            border-bottom: 5px solid transparent;
            border-left: 12px solid black;
            top:-4px;
            right:-3px;
        }
    </style>
</head>
<body>
    <div class="arrow"></div>
</body>
</html>