[教學] CSS 氣泡提示框 (tooltip/speech bubble/bubble with arrow/balloon)

May 08, 2016

分類標籤:css

前端元件hover的時候顯示氣泡提示框(tooltip/balloon)是常見的效果,也有許多現成的library如Balloon.css可用。這篇教學教你如何用純CSS手刻。

See the Pen css-balloon by Shubo Chao (@shubochao) on CodePen.

目錄

氣球的形狀

氣球的形狀怎麼做?其實可以把它看成一個三角形(突出的尖端)加一個有圓角的方形(本體),用純CSS的話可以用:before虛擬元素做出三角形,:after做出方形。

三角形:設定上方邊界的顏色及寬度(三角形的高,8px),下方無邊界,左右邊界設定透明及寬度(三角形的底,8px + 8px = 16px):

&:before {
  content: "";
  border-top: solid 8px $balloon-color;
  border-left: solid 8px transparent;
  border-right: solid 8px transparent;
}

氣球的本體:利用content屬性秀出文字內容,attr(balloon-data)會去讀元素的balloon-data屬性。

&:after {
  content: attr(balloon-data);
}

可以直接在html元素裡用balloon-data屬性設定氣球的文字內容:

<button
  class="button balloon"
  balloon-data="Hello."> <!-- Balloon content -->
  Hover me!
</button>

如何定位

讓氣球相對於按鈕定位:調整position屬性,利用absolute元素的定位,是相對於他所處上層容器的特性,來達到相對定位的效果。參考:關於 position 屬性

.balloon {
  position: relative;
  &:before, &:after {
    position: absolute;
    ...
  }
  ...
}

調整氣球位於按鈕上方並水平置中:調整lefttransform屬性。參考:How to center a “position: absolute” element

Adding top/left of 50% moves the top/left margin edge of the element to the middle of the parent, and translate() function with the (negative) value of -50% moves the element by the half of its size. Hence the element will be positioned at the middle.

&:before, &:after {
  bottom: 100%;
  left: 50%;
  transform: translate(-50%, 0);
}

Hover效果

hover前後改變opacity屬性並設定轉場效果:

&:before, &:after {
  transition: all 0.18s ease-out 0.18s;
  opacity: 0;
}

&:hover:before, &:hover:after {
  opacity: 1;
}

心得

最後的成品:

See the Pen css-balloon by Shubo Chao (@shubochao) on CodePen.

CSS真是博大精深啊,光是一個常見的氣球也用到不少技巧!像是

  • before, after虛擬元素
  • position: absolute;
  • CSS transform等。

參考資料:


Profile picture

Shubo Chao 軟體工程師,目前大多專注於前端開發