Let the user decide the size and alignment of mermaid diagrams

To align all mermaid diagrams, you can write the following in your obsidian.css file (you can replace “center” with “left” or “right” if you choose to do so):

div.mermaid {
    text-align: center;
}

Adjusting the width and height of mermaid diagrams is a bit trickier, but I found the following solution.

EDIT: While the solution below does technically work, please replace anywhere I’ve written svg[ig^="m"][width][height][viewBox] { *desired code* } in the css below with the much simpler .mermaid svg { *desired code* }. This simpler solution was offered by @smcllns in a later post on this thread.

The example below sets the width of the mermaid diagrams as 400px while preserving the aspect ratio:

svg[id^="m"][width][height][viewBox] {
    width: 400px;
    height: auto;
}

You can also have several variations of the above code. A couple of examples include:

  • A width of 80% of the current window’s width:

    svg[id^="m"][width][height][viewBox] {
        width: 80%;
        height: auto;
    }
    
  • A minimum width of 350px and a maximum width of 600px:

    svg[id^="m"][width][height][viewBox] {
        min-width: 350px;
        max-width: 600px;
        width: 80%;
        height: auto;
    }
    

I hope this helps! Also, for anyone interested, the steps I used to find this solution were the following:

  1. I used Ctrl+Shift+I (on Windows) to open the obsidian developer tools while in preview mode. Then, I inspected the mermaid elements in my page and found that they have randomly generated id attributes all starting with the letter “m”. An example was the following:

    <svg id="me4c26fffe5bb1328" ...>
    
  • N.B. The mermaid id attribute changes for an obsidian diagram after an obsidian site is published, so targeting a particular id using css and hoping for those changes to carry over is not feasible.
  1. Through some searching online, I found that I can change the attributes of an html element whose name starts with a string by following the recipe:

    element_name[attribute_name^="starting_string"] { *desired code changes here* }
    
  • In this case, the html element is svg, the attribute name is id, and the starting string is “m”, so I would have to write:

    svg[id^="m"] { *desired code here* }
    
  • However, there may be other svg elements on a page that also have their id attribute start with “m”, so the above solution isn’t too specific.

  1. In pursuit of greater specificity, I added [width], [height], and [viewBox] because each mermaid diagram I saw also had width, height, and viewBox attributes:

    svg[id^="m"][width][height][viewBox] { *desired code here* }
    

Finally, I have to say that I only tested this on mermaid flowcharts, so if it doesn’t work for other types of mermaid diagrams, please let me know.

34 Likes