您现在的位置是:网站首页>列表内容

CSS实现对话框小尾巴功能_CSS教程_CSS_网页制作_

2021-09-10 19:36:38 717人已围观

简介 对话框小尾巴,估计大家在实际开发中应该经常遇到过,省事点的就是叫设计小姐姐给切个带小尾巴的背景图,那不省事的呢?这篇文章主要介绍了CSS对话框小尾巴,需要的朋友可以参考下

对话框小尾巴,估计大家在实际开发中应该经常遇到过,省事点的就是叫设计小姐姐给切个带小尾巴的背景图,那不省事的呢?

边框的魔法

在css3出来之前,若通过css来实现小尾巴效果,可能使用最多的是通过如下的hack方式:

我是快乐的小尾巴的爸爸

.tooltip { position: relative; background-color: silver; width: 200px; height: 50px; border-radius: 0.25em; display: flex; justify-content: center; align-items: center; border:1px solid red; } .triangle { display: block; height: 0px; width: 0px; border: 10px solid transparent; border-top-color: silver; background:red; position: absolute; bottom: -20px; left: calc(50% - 10px); }

效果如下:

不设置 triangle 宽高,设置 border 10像素的透明边框,然后设置 top 方向边框颜色和父元素一致就可完成这样的效果,同理,变换小尾巴箭头方向只需要在top,bottom,left,right方向上单独设置不同的边框颜色即可。

这种方式是挺奇妙的,但存在以下几个问题:

tooltip

被咬了一口的样式,残缺的美~

clip-path

针对以上问题,现在有了一种特别好的方式,就是通过css3新增的clip-path属性来实现

clip-path属性可以创建一个只有元素的部分区域可以显示的剪切区域,区域内的部分显示,区域外的隐藏

css代码如下:

.triangle {
    display: block;
    height: 20px;
    width: 20px;
    background-color: inherit;
    border: inherit;
    position: absolute;
    bottom: -10px;
    left: calc(50% - 10px);
    // ---关键代码 start---
    clip-path: polygon(0% 0%, 100% 100%, 0% 100%);
    transform: rotate(-45deg);
    // ---end---
    border-radius: 0 0 0 2px;
}

我们可以看到 triangle 继承了父元素 tooltip 的边框颜色以及背景色,同时我们还设置了小尾巴2个像素的圆角。

其中 polygon 多边形的坐标如下:

深绿色块就是我们要显示的区域,然后逆时针翻转45度就成了我们想要的样式。

多么好的方式呀!

那浏览器兼容性如何呢?我查看了下Caniuse这个网站,除了老IE基本其它浏览器都支持,所以开心的用起来吧!

最后提供一个 sass 的mixin,参数是上下左右四个方向。

@mixin triangleMixin ($direction) {
  background-color: inherit;
  border: inherit;
  clip-path: polygon(0% 0%, 100% 100%, 0% 100%);
  
  @if( $direction == left ) {
    transform: rotate(45deg);
  } @else if( $direction == right ) {
    transform: rotate(-135deg);
  } @else if( $direction == down ) {
    transform: rotate(-45deg);
  } @else {
    transform: rotate(135deg);
  }
}

总结

以上所述是小编给大家介绍的CSS实现对话框小尾巴功能,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!

发布内容
-六神源码网