Leaflet tooltip can't have max width and text wrapping

Viewed 131

I made this codepen to demonstrate the problem: https://codepen.io/mbbbackus/pen/ExQbbZp

Javascript:

var map = L.map('map', {
    center: [38.89, -77.03],
    zoom: 11
});
 

var tiles = new L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
  minZoom: '15'}).addTo(map);

var marker = L.marker(
  [38.89, -77.03],
  { 
    draggable: true,
    title: "",
    opacity: 0.75
});

marker.addTo(map).bindTooltip("<p1><b>The White House</b><br>Landmark, historic home & office of the United States president, with tours for visitors.</p1>", {className: 'tooltip'})

CSS:

#map { 
  height: 100vh;
}

.leaflet-popup-content-wrapper {
  width: 100%;
}

.tooltip {
        max-width: 15rem;
        white-space: initial;
}

HTML:

<div id="map"></div> 

I want the tooltip to expand in width as is necessary until the it hits the max width, at which point the text should start wrapping. You'll see in the codepen that instead of expanding to the max width, my tooltip gets really skinny and wraps the text after only one or two words each line.

What do I need to change so that I can set a max width and still wrap text properly?

1 Answers

Changing the CSS to:

.tooltip {
    max-width: 15rem;
    width: max-content;
    white-space: normal;
}

worked for me.

.leaflet-tooltip is a CSS class defined by leaflet itself and applied to tooltips. white-space is defined in it to be nowrap. That needed to be overridden.

max-content allows the div to grow as wide as it needs to be up to max-width before wrapping is applied.

The wrapping behavior is just the default.

Related