如何用CSS创建带三角尾部的模态窗口?
问题描述

我已创建三角箭头样式:
&--triangle { position: absolute; top: 40px; left: 25%; width: 0; height: 0; border-left: 40px solid transparent; border-right: 40px solid transparent; border-bottom: 50px solid $color-white; z-index: 999; }
我已创建弹窗样式:
&--modal { width: 200%; @include flexCenter(column); min-height: 100px; position: absolute; top: 70px; right: 0; background-color: $color-white; padding-top: 10px; z-index: 998; box-shadow: 0 4px 4px rgba(0, 0, 0, .25); } }
但我需要为包含三角尾部的整个窗口添加边框和阴影效果。
解决方案
要实现包含三角的整体边框和阴影,核心是让三角与弹窗的视觉效果统一,这里提供两种可行方案:
方案一:给三角添加阴影/边框层
通过伪元素给三角叠加一层深色底层,模拟阴影和边框,与弹窗样式匹配:
修改三角的CSS代码:
&--triangle { position: absolute; top: 40px; left: 25%; width: 0; height: 0; z-index: 999; /* 阴影/边框底层 */ &::before { content: ''; position: absolute; border-left: 42px solid transparent; border-right: 42px solid transparent; border-bottom: 52px solid rgba(0, 0, 0, .25); /* 和弹窗阴影颜色一致 */ transform: translate(-50%, -2px); /* 偏移形成阴影效果 */ } /* 白色三角上层 */ &::after { content: ''; position: absolute; border-left: 40px solid transparent; border-right: 40px solid transparent; border-bottom: 50px solid $color-white; } }
同时给弹窗添加边框:
&--modal { width: 200%; @include flexCenter(column); min-height: 100px; position: absolute; top: 70px; right: 0; background-color: $color-white; padding-top: 10px; z-index: 998; box-shadow: 0 4px 4px rgba(0, 0, 0, .25); border: 1px solid #ddd; /* 按需调整边框颜色 */ }
方案二:用父容器包裹弹窗和三角
将弹窗与三角放入同一父容器,给父容器添加边框和阴影,三角通过伪元素模拟边框与父容器衔接:
/* 父容器 */ &--modal-wrapper { position: absolute; top: 70px; right: 0; width: 200%; padding-top: 50px; /* 预留三角的高度空间 */ background-color: $color-white; border: 1px solid #ddd; box-shadow: 0 4px 4px rgba(0, 0, 0, .25); z-index: 998; } /* 弹窗内容 */ &--modal { min-height: 100px; @include flexCenter(column); padding-top: 10px; } /* 三角箭头 */ &--triangle { position: absolute; top: 0; left: 25%; width: 0; height: 0; border-left: 40px solid transparent; border-right: 40px solid transparent; border-bottom: 50px solid $color-white; /* 模拟边框 */ &::before { content: ''; position: absolute; border-left: 41px solid transparent; border-right: 41px solid transparent; border-bottom: 51px solid #ddd; /* 和父容器边框同色 */ transform: translate(-50%, 2px); z-index: -1; } }
两种方案都能实现包含三角的整体边框与阴影效果,可根据实际布局需求选择。
内容的提问来源于stack exchange,提问作者Oleksii
相关产品推荐
相关产品推荐

