Skip to content

Instantly share code, notes, and snippets.

@jasonzhouu
Last active March 11, 2020 09:52
Show Gist options
  • Save jasonzhouu/9a6dbc580b125b6a07e1d1534581b4d9 to your computer and use it in GitHub Desktop.
Save jasonzhouu/9a6dbc580b125b6a07e1d1534581b4d9 to your computer and use it in GitHub Desktop.
提示框

第324天 使用css实现悬浮提示文本

captured

html

<div class="haveTips" tips='hello world'>Lorem ipsum dolor</div>

css

div.haveTips {
    background-color: #F7F5F1;
    color: #BBA985;
    font-family: sans-serif;
    padding: 1em;
    border-radius: 10px;
    position: relative;
    cursor: pointer;
}

div.haveTips::after {
    content: attr(tips);
    padding: 5px;
    background-color: #B4A078;
    box-shadow: 0 0 5px #B4A078;
    color: white;
    min-width: 5em;
    max-width: 100%;
    text-align: center;
    border-radius: 5px;

    position: absolute;
    bottom: 100%;
    left: 50%;
    transform: translate(-50%, -10px);

    opacity: 0;
    transition: all 0.5s;
}

div.haveTips:hover::after {
    opacity: 1;
}

div.haveTips::before {
    content: '';

    width: 0;
    height: 0;
    border: 6px solid transparent;
    border-top-color: #B4A078;

    position: absolute;
    top: -10px;
    left: calc(50% - 6px);

    opacity: 0;
    transition: all 0.5s;
}

div.haveTips:hover::before {
    opacity: 1;
}

原理

对话气泡类似,提示框也由矩形和小三角组成。

  1. 使用选择器::after创建的伪元素作为提示框
  • 使用选择器:hover::after设置样式,使其悬浮时显示
  • 结合absolute positiontransform translate将提示框放到期望的位置:水平方向中心对其,垂直方向隔开一定空隙。
    • bottom: 100%,使其放在父组件的上边界之外,下边缘位于父组件的上边缘
    • left: 50%,使其左边缘位于父组件的中心线
    • translate(-50%, -10px),左移自身宽度的50%,上移10px,与父组件保持一点距离
    • content: attr(tips),获取html标签的tips属性作为内容,方便在html标签内指定提示框内容
  1. 使用选择器::before创建的伪元素作为小三角形箭头
  • 利用border属性创建三角形,参考构建三角形的方法
  • 使用上述类似的移动方法,将其移到期望位置
  • 使用上述一样的方法,使其悬浮时显示

在左右移动时,同时用了 lefttranslate 这2个属性,它们的功能类似,为什么不只用 left呢?

因为它们的百分比计算基数不同:

  • left的基数是父组件的宽度
  • translate的基数是自身的宽度

两个结合起来,可以使提示框与父组件中心对齐。


参考:https://lhammer.cn/You-need-to-know-css/#/zh-cn/poptip

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment