使用 CSS 绘制三角形的几种方法

我最近重新设计我的网站,并希望创建工具提示。 使得这很简单,但我也希望我的工具提示为特色的三角指针。 我是一个灾难,当涉及到的图像和需要,以使图像的每个颜色提示,我想使我重新思考我重新设计的前景。 我很幸运,MooTools 的核心开发者达伦 – 沃德尔与我共享一个伟大的效果 CSS 的三角形。 使用纯 CSS,你可以创建跨浏览器兼容的三角形用很少的代码。

使用 CSS 绘制三角形的几种方法

运行效果参见:http://run.wenjiangs.com/code/#/?code=Sxi5OL26

使用 Border 边框创建三角形

/* create an arrow that points up */

div.arrow-up {

    width: 0;

    height: 0;

    border-left: 5px solid transparent;  /* left arrow slant */

    border-right: 5px solid transparent; /* right arrow slant */

    border-bottom: 5px solid #2f2f2f; /* bottom, add background color here */

    font-size: 0;

    line-height: 0;

}

/* create an arrow that points down */

div.arrow-down {

    width: 0;

    height: 0;

    border-left: 5px solid transparent;

    border-right: 5px solid transparent;

    border-top: 5px solid #2f2f2f;

    font-size: 0;

    line-height: 0;

}

/* create an arrow that points left */

div.arrow-left {

    width: 0;

    height: 0;

    border-bottom: 5px solid transparent;  /* left arrow slant */

    border-top: 5px solid transparent; /* right arrow slant */

    border-right: 5px solid #2f2f2f; /* bottom, add background color here */

    font-size: 0;

    line-height: 0;

}

/* create an arrow that points right */

div.arrow-right {

    width: 0;

    height: 0;

    border-bottom: 5px solid transparent;  /* left arrow slant */

    border-top: 5px solid transparent; /* right arrow slant */

    border-left: 5px solid #2f2f2f; /* bottom, add background color here */

    font-size: 0;

    line-height: 0;

}

秘密到这些三角形是创造巨大的边界的方向你想要的三角形指向两个垂直的两侧。 使另一侧的边框相同的大小与什么颜色你想要的工具提示为背景色。  你可以用颜色的三角形的任何颜色、尺寸,并且在任何方​​向。 最好的部分是,有达到这种效果需要非常少的代码。

使用 :before:after 绘制 CSS 三角形

上面的 CSS 例子使用真实的元素,但如果你不希望添加一个三角形? CSS 的三角形可以与伪元素来创建,这是一个完美的情况下,工具提示。 这里是你如何能做到这样:

div.tooltip {

    /* tooltip content styling in here; nothing to do with arrows */

}

/* shared with before and after */

div.tooltip:before, div.tooltip:after {

    content: ' ';

    height: 0;

    position: absolute;

    width: 0;

    border: 10px solid transparent; /* arrow size */

}

/* these arrows will point up */

/* top-stacked, smaller arrow */

div.tooltip:before {

    border-bottom-color: #fff;  /* arrow color */

    /* positioning */

    position: absolute;

    top: -19px;

    left: 255px;

    z-index: 2;

}

/* arrow which acts as a background shadow */

div.tooltip:after {

    border-bottom-color: #333;  /* arrow color */

    /* positioning */

    position: absolute;

    top: -24px;

    left: 255px;

    z-index: 1;

}

边框侧面添加的颜色是箭头指针的另一侧。 也并不是说你不需要同时使用 :before:after 伪元素-你只需要使用一个。 第二个箭头可以,不过被用作背景阴影或背景的边界。

以上是 使用 CSS 绘制三角形的几种方法 的全部内容, 来源链接: utcz.com/p/231809.html

回到顶部