css底部带有三角形箭头的圆角矩形效果

快乐打工仔 分类:实例代码

分享一段代码实例,它实现了底部带有三角形箭头的圆角矩形效果。

比较常见于鼠标悬浮的时候弹出的tip提示效果,代码实例如下:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.pipipi.net/" />
<title>前端教程网</title>
<style type="text/css">
.antzone {
  margin: 200px;
  border: 1px solid black;
  width: 100px;
  height: 40px;
  position: relative;
  border-radius: 5px;
}
.antzone:before {
  border: 8px solid transparent;
  border-top-color: black;
  position: absolute;
  content: "";
  left: 50%;
  top: 100%;
  margin-left: -8px;
}
.antzone:after {
  border: 8px solid transparent;
  border-top-color: #FFFFFF;
  position: absolute;
  content: "";
  left: 50%;
  top: 100%;
  margin-left: -8px;
  margin-top: -1px;
}
</style>
</head>
<body>
<div class="antzone"></div>
</body>
</html>

上面的代码实现了我们的要求,下面介绍一下它的实现过程。

.antzone {
  margin: 200px;
  border: 1px solid black;
  width: 100px;
  height: 40px;
  position: relative;
  border-radius: 5px;
}

设置矩形的相关样式。

设置其边框为黑色,长宽分别为100px和40px。

将其设置为相对定位,为了作为内部定位元素的定位参考对象。

最后将其设置为圆角。

.antzone:before {
  border: 8px solid transparent;
  border-top-color: black;
  position: absolute;
  content: "";
  left: 50%;
  top: 100%;
  margin-left: -8px;
}

通过伪元素选择器:before在矩形元素中添加一个元素。

此元素的边框厚度是8px,并且没有设置元素的长宽,采用绝对定位的元素,如果不显示设置其尺寸,那么其尺寸为0。

通过四个边框我们可以挤出四个三角形,具体可以参阅css实现三角形效果详解一章节。

设置上边框的颜色为黑色,这个会配合我们实现黑色三角形效果。

left: 50%和margin-left: -8px能够使伪元素水平居中。

top: 100%将伪元素定位于矩形的底部外缘。

.antzone:after {
  border: 8px solid transparent;
  border-top-color: #FFFFFF;
  position: absolute;
  content: "";
  left: 50%;
  top: 100%;
  margin-left: -8px;
  margin-top: -1px;
}

这段代码和上一段代码的功能是一样,不同无非是有两点:

(1).使用的:after伪对象选择器,在这里和:before没什么区别。

(2).margin-top: -1px的作用是露出:before伪元素选择器创建的元素的1px的黑色边框。

回复

我来回复
  • 暂无回复内容