Text font changes when embedded in website

I have the following map I created: BMI Classification Prevalence - 2018 Survey Estimates / Ben Lobo / Observable

I was able to successfully embed it into a website a while back: TJHD - BMI Classification Prevalence

However, when I revisited this page I noticed that the font for the legend is no longer correct. It used to appear exactly as it shows in the Observable notebook, but now it looks like both the font type and size have changed, and I cannot figure out why.

The embedding page includes a stylesheet that sets a font-size of 2rem for any .title element. Your legend has the class title. :slight_smile:

Ah, I see. Thank you for including the screenshot as it allowed me to understand how you had found the issue.

Is there a standard way of fixing this type of issue? Should I try and remove the title class on the legend?

If you don’t want to inline your CSS, you can prepend a random “namespace” to your classes, so that they’re guaranteed to not conflict with any other classes on that page.


// Creates an incrementing unique ID.
const prefix = DOM.uid('my-css').id;
const titleClass = `${prefix}-title`;

Excuse my ignorance, but where would I place these lines of code?

No worries, there’s nothing to excuse! :slight_smile:

In your specific example, the .title class is set by the @d3/color-legend notebook. But since there aren’t any styles that would require it, you can simply remove it. In your chart cell, right before you return svg.node(), add the following line:

  svg.selectAll('.title').classed('title', false);

If you wanted to use the title class (e.g. to change the font size), you could do this instead (each code block is a separate cell):

prefix = DOM.uid('css').id
css_style = html`<style>
  /* ... */

  .${prefix}-title { font-size: .8em }
chart = {
  // ...

  // Replace title class
    .classed('title', false)
    .classed(`${prefix}-title`, true);

  return svg.node();

Note that there is also a more advanced method. You can create a so-called “shadow DOM”, which prevents styles outside of the shadow DOM from affecting your elements, and vice-versa.

A simple example can be found in this notebook:

If you want to use this feature, be sure that your targeted browsers and devices support it.

1 Like

I ended up using the first solution because (as you pointed out) there aren’t any styles that require it. I will keep in mind the two alternate solutions for the future.

Thanks again for your patience and very clear answer.