csstwitter-bootstraptwitter-bootstrap-tooltipbootstrap-5

Using Bootstrap 5 to create custom tooltips


I am using Bootstrap 5 and am attempting to create a custom tooltip. I see the markup used in the Bootstrap 5 documentation here.

Bootstap 5 Tooltips Markup

I gathered (and looked online) that the tooltips are not in the calling element and are siblings. I am trying to use a custom class like so with the below markup.

// CSS test option #1
.custom-tooltip + .tooltip > .tooltip-inner
{
    text-align: left;
    max-width: 500px;
}

// CSS test option #2
.custom-tooltip ~ .tooltip > .tooltip-inner
{
    text-align: left;
    max-width: 500px;
}

<span class="custom-tooltip" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-html="true" title="The tooltip text<br/>Extra textC">
    <svg ... ></svg>
</span>

So if you only use .tooltip-inner, obviously, it works fine, but I do not want a global tooltip and need to have different custom tooltips.


Solution

  • (This one took some time to figure out since the canonical answer does not work --- this may well be a JSFiddle thing, or a BS5 bug .. not sure.)

    The documented approach is to add your custom class to the customClass option, like so:

    <span data-bs-customClass="custom-tooltip" data-bs-toggle="tooltip" data-bs-html="true" title="The tooltip text<br/>Extra text">
      STUFF
    </span>
    

    But I can't get that to work on this JSFiddle. This is because the html is rendered (on Chrome) in all lowercase and the "C" in "customClass" renders "customclass" .. so the BS5 JS never picks it up. The workaround is to pass that option in the tooltip initialiser, like so:

    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
    var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
      return new bootstrap.Tooltip(tooltipTriggerEl, {
        'customClass': 'custom-tooltip'
      })
    })
    

    And then your CSS should work as normal with:

    .custom-tooltip.tooltip > .tooltip-inner
    {
        text-align: left;
        max-width: 500px;
    }
    

    EDIT:

    Turns out this was fixed ... correct method is to add a hyphen "-" before an uppercase option and use the lowercase form, like so:

    <span data-bs-custom-class="custom-tooltip" data-bs-toggle="tooltip" data-bs-html="true" title="The tooltip text<br/>Extra text">
      STUFF
    </span>
    

    The initialiser should then also exclude that option (adding it overrides the data attribute). Initialiser is a as per docs:

    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
    var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
      return new bootstrap.Tooltip(tooltipTriggerEl)
    })