返回
样式打造伪元素和scss模拟tootip,让设计更灵动更统一
前端
2023-11-19 23:20:09
伪元素和scss模拟tootip,让设计更灵动更统一
在页面设计中,有时候,我们需要在一段文字或者按钮添加一个提示组件。原先一般通过模态组件模拟一个,但是现在我们可以只通过样式就可以做到,同时为了支持扩展,我们使用scss来书写。
首先,我们需要一个箭头,支持四个方向、大小和颜色的扩展:
/* 箭头样式 */
.arrow {
width: 10px;
height: 10px;
border-right: 1px solid #000;
border-bottom: 1px solid #000;
transform: rotate(45deg);
position: absolute;
top: 50%;
left: 50%;
margin-top: -5px;
margin-left: -5px;
}
/* 箭头方向 */
.arrow-top {
transform: rotate(135deg);
top: 100%;
margin-top: -10px;
}
.arrow-bottom {
transform: rotate(315deg);
top: 0;
margin-top: 0;
}
.arrow-left {
transform: rotate(225deg);
left: 100%;
margin-left: -10px;
}
.arrow-right {
transform: rotate(45deg);
left: 0;
margin-left: 0;
}
/* 箭头颜色 */
.arrow-primary {
border-right-color: #007bff;
border-bottom-color: #007bff;
}
.arrow-success {
border-right-color: #28a745;
border-bottom-color: #28a745;
}
.arrow-warning {
border-right-color: #ffc107;
border-bottom-color: #ffc107;
}
.arrow-danger {
border-right-color: #dc3545;
border-bottom-color: #dc3545;
}
/* 箭头大小 */
.arrow-large {
width: 20px;
height: 20px;
margin-top: -10px;
margin-left: -10px;
}
.arrow-small {
width: 5px;
height: 5px;
margin-top: -2.5px;
margin-left: -2.5px;
}
然后我用用::before元素构造一个tooltip。
/* tooltip样式 */
.tooltip {
position: absolute;
padding: 10px;
background-color: #fff;
border: 1px solid #000;
border-radius: 5px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
z-index: 9999;
}
/* tooltip方向 */
.tooltip-top {
top: -10px;
left: 50%;
margin-left: -100px;
}
.tooltip-bottom {
top: 110%;
left: 50%;
margin-left: -100px;
}
.tooltip-left {
top: 50%;
left: -10px;
margin-top: -50px;
}
.tooltip-right {
top: 50%;
left: 110%;
margin-top: -50px;
}
/* tooltip颜色 */
.tooltip-primary {
background-color: #007bff;
color: #fff;
}
.tooltip-success {
background-color: #28a745;
color: #fff;
}
.tooltip-warning {
background-color: #ffc107;
color: #000;
}
.tooltip-danger {
background-color: #dc3545;
color: #fff;
}
/* tooltip大小 */
.tooltip-large {
padding: 20px;
}
.tooltip-small {
padding: 5px;
}
最后,我们可以通过伪类来改变提示组件的状态,比如:hover的时候,提示组件显示;离开的时候,提示组件隐藏。
/* hover的时候,提示组件显示 */
.tooltip:hover {
visibility: visible;
}
/* 离开的时候,提示组件隐藏 */
.tooltip:not(:hover) {
visibility: hidden;
}
通过以上方法,我们可以轻松地用scss创建一个漂亮的tooltip。