Wednesday, July 6, 2016

Tooltips sans Bootstrap

If you're using Bootstrap to do tooltips, you're doing it wrong, and your site's performance probably shows you're doing it wrong.

Here's an example I've seen recently

HTML
<a href="#" data-toggle="tooltip" title="Get you some of that">   <h2>GYSOT</h2> </a>

Here are a few problems with this approach:

  1. if you're doing it this way you're not only using the Bootstrap CSS file (which to be honest is a little bloated) but you're also using Bootstrap JS
  2. your code is not semantic
  3. your code has a few extra accessibility issues

It would be more semantic if the markup was something like…
HTML
<h2 data-toggle="tooltip" title="Get you some of that">GYSOT</h2>

...but that doesn't really solve any performance issues your users are experiencing because of all the extra goodies Bootstrap includes that you're not using – and it doesn't solve the accessibility issues. That's why it would be nicer if we wrote the markup as…

HTML
<h2 aria-label="Get you some of that" class="has-tooltip">GYSOT</h2>

Here's the thing. Not only is this less markup, but here's all the CSS you'll need to put in a tooltip.

CSS
.has-tooltip {   display:inline;   position:relative; } .has-tooltip:focus:after, .has-tooltip:hover:after {   background:rgba(200, 200, 200, .9);   border:0.1em solid rgb(128, 128, 128);   border-radius:0.3em;   bottom:1.3em;   color:rgb(0, 0, 0);   content:attr(aria-label);   left:0;   padding:0.1em;   position:absolute;   z-index:1; } .has-tooltip:focus:before, .has-tooltip:hover:before {   border-color:rgb(128, 128, 128) transparent;   border-left:0.3em solid transparent;   border-right:0.3em solid transparent;   border-top:0.3em solid rgb(128, 128, 128);   bottom:1em;   content:"";   left:50%;   position:absolute;   z-index:2; }


It really is that simple to display a tooltip directly above some text and to make the content of the tooltip directly accessible.

A couple little notes - if you want to display the tooltip on the bottom of the you'll have to adjust the bottom values for both the before and after pseudoclass rules and if you want to display the tooltip with a different font or font-size you'll have to adjust those on the before and after pseudoclasses as well. All the detailed customization aside, this should get to started down the road to ditching Bootstrap.

Happy coding.

No comments:

Post a Comment