Search code examples
htmlcssletter-spacing

Why does em unit in CSS not work as expected in this case?


I am learning about letter spacing. I am using the em unit here for letter spacing. The element on which I use the unit does not have any parent except html. But if I change the font size of the HTML, the letter spacing does not change.

At first, the HTML tags were not present in this code. I tried adding them to see if it works. I also tried to set font-size at :root, but none worked.

html {
  font-size: 2px
}

h1 {
  font-family: 'COUTUREBold';
  margin: 0;
  font-size: 38px;
}

.wide {
  font-size: 24px;
  letter-spacing: .5em;
}

.narrow {
  font-size: 48px;
  letter-spacing: -.15em;
}
<link rel="stylesheet" media="screen" href="https://fontlibrary.org//face/couture" type="text/css" />

<h1>Hello World!</h1>
<h1 class="wide">Hello World!</h1>
<h1 class="narrow">Hello World!</h1>

Code: https://codepen.io/KAEKrishCodes/pen/ExOYxPY


Solution

  • If you want the letter spacing to be affected by the font size of the html element, you can use the rem unit instead of em for letter spacing. The rem unit is relative to the root element's font size, which is, in most cases, the html element. You'd want to change all mentions of em into rem in your code.

    For example:

    letter-spacing: -.15em;
    

    Would become:

    letter-spacing: -.15rem;
    

    Not sure whether I'm correct on whether this is what you want to do, but I hope it helps.