How to fix CSS problem with Letter-Spacing and right-aligned text?

Asked

Viewed 159 times

4

I and have a situation in which I have a container with two lines of text inside aligned to the right. Only that one of the lines is with the property letter-spacing: 15px; Increase the spacing between characters.

The problem is that the letter-spacing increases the space just to the right, this way the text is not aligned correctly on the right leaving an empty space on the right between the end of the text and the container.

I know that putting one margin-right negative at the same value as letter-spacing i corrected that. Only I have text of various sizes with letter-spacing of various sizes and I don’t want to keep repeating a margin-right for each letter different.

Is there any way to automate this without having to keep repeating the negative value in margin-right?

Is there any way to use CSS Variables to automate this? Like if my letter-spacing for X has how to automatically pass this value to my margin-right?

p + p {
    letter-spacing: 15px;
}
p {
  color: orangered;
  text-align: right;
  font-size: 30px;
  font-family: Arial, "Helvetica Neue", Helvetica, sans-serif;
  text-transform: uppercase;
}
.box {
  width: 500px;
  border: 1px solid;
}
<div class="box">
  <p>Titlem</p>
  <p>taglinem</p>
</div>

1 answer

2


If you declare the value as a variable and use the Calc function to invert it in the margin-right, you can get around the problem.

p + p {
    --espaco : 15px;
    letter-spacing: var(--espaco);
    margin-right: calc(var(--espaco) * -1);
}
p {
  color: orangered;
  text-align: right;
  font-size: 30px;
  font-family: Arial, "Helvetica Neue", Helvetica, sans-serif;
  text-transform: uppercase;
}
.box {
  width: 500px;
  border: 1px solid;
}
<div class="box">
  <p>Titlem</p>
  <p>taglinem</p>  
</div>

  • Dude, I think it’s right around the corner. As I intend to use in several elements with different values I preferred to create a class just like Letter and margin, and a var with value 0 in :root, so I only override the value in the class of the element that also has Letter... To clarify https://codepen.io/hugocsl/pen/wQqpRg Thanks for the tip!

  • 2

    Great, I just noticed another detail, in .box it would take a overflow-x : hidden. Selects the text with the letter-spacing for you to see.

  • It would really be prudent to use the overflow!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.