Centering h1 and h2 with CSS not working unless header text is at least two lines long

Things I have tried

I am currently trying to style my notes and I want the h1 and h2 headers to be centered always, for this I have this snippet:

.cm-s-obsidian .cm-header-1, .markdown-preview-view h1 {
  font-family: 'SF Pro Display', bold;
  font-size: 54px;
  width: fit-content;
  margin-top: 10px;
  text-align: center;
  margin-bottom: 10px;
  line-height: 45px;
}

.cm-s-obsidian .cm-header-1, .markdown-preview-view h2 {
  font-family: 'SF Pro Display', black;
  font-size: 30px;
  width: fit-content;
  margin-top: 10px;
  text-align: center;
  margin-bottom: 10px;
  line-height: 25px;
}

.mod-cm6 .cm-editor .HyperMD-header-1 {

  font-family: 'SF Pro Display', black;
  font-size: 54px;
  width: fit-content;
  margin-top: 10px;
  text-align: center;
  margin-bottom: 10px;
  line-height: 45px;
}

.mod-cm6 .cm-editor .HyperMD-header-2 {

  font-family: 'SF Pro Display', black;
  font-size: 30px;
  width: fit-content;
  margin-top: 10px;
  text-align: center;
  margin-bottom: 10px;
  line-height: 25px;
}

It doesn’t work unless the header text is long enough it spans two lines, if it does it will be centered, if it doesn’t it stays left-aligned. Is there something I’m doing wrong? How could I fix this?

Thanks!

width: fit-content; seems to interfere. If you remove that, it should work.

2 Likes

@Olondre is right. width: fit-content will never exceed max-content, meaning you won’t see the effects of text-align: center until one of the lines is shorter than max-content (in other words, you need at least two lines to see it working). If you have width: fit-content for a reason, then perhaps you might want to use margin-inline: auto instead of text-align: center.

2 Likes

@Olondre @geoffb Thank you very much! Fixed!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.