Tooltips for mobile browsers

后端 未结 9 1972
后悔当初
后悔当初 2020-12-07 13:16

I currently set the title attribute of some HTML if I want to provide more information:

An

9条回答
  •  爱一瞬间的悲伤
    2020-12-07 13:51

    Here is a CSS only solution. (Similar to @Jamie Pate 's answer, but without the JavaScript.)

    We can use the pseudo class :hover, but I'm not sure all mobile browsers apply these styles when the element is tapped. I'm using pseudo class :focus because I'm guessing it's safer. However, when using pseudo class :focus we need to add tabindex="0" to elements that don't have a focus state intrinsically.

    I'm using 2 @media queries to ensure all mobile devices are targeted. The (pointer: coarse) query will target any device that the primary input method is something "coarse", like a finger. And the (hover: none) query will target any device that the primary pointing system can't hover.

    This snippet is all that's needed:

    @media (pointer: coarse), (hover: none) {
          [title] {
            position: relative;
            display: inline-flex;
            justify-content: center;
          }
          [title]:focus::after {
            content: attr(title);
            position: absolute;
            top: 90%;
            color: #000;
            background-color: #fff;
            border: 1px solid;
            width: fit-content;
            padding: 3px;
          }
        }
    

    /*Semantic Styling*/
    body {
      display: grid;
      place-items: center;
      text-align: center;
      height: 100vh;
    }
    
    a {
      height: 40px;
      width: 200px;
      background: #fa4766;
      color: #fff;
      text-decoration: none;
      padding: 10px;
      box-sizing: border-box;
      border-radius: 10px;
    }
    
    /*Functional Styling*/
    @media (pointer: coarse), (hover: none) {
      [title] {
        position: relative;
        display: flex;
        justify-content: center;
      }
      [title]:focus::after {
        content: attr(title);
        position: absolute;
        top: 90%;
        color: #000;
        background-color: #fff;
        border: 1px solid;
        width: fit-content;
        padding: 3px;
      }
    
    }
    Tag with Title

    Obviously, you'll need to open this on a mobile device to test it. Here is a Pen with the same code.

提交回复
热议问题