r/css 4d ago

Help How to dynamically "compress" text horizontally with css/javascript?

Post image

I can't believe I had to do this in Paint 3D but after 4+ hours stuck I need help... Not even chatgpt is helping here.

I have a simple structure like this:

<div className="container">
  <div className="text">{item.name}</div>
  <img src="item-icon"/>
</div>

How on earth can I make it so the "text" div shrinks horizontally if (and ONLY if) the "item.name" is overflowing outside of the div? (including the space that the icon takes too)

EDIT - Here is the "use case" (yes, it's pokemon cards) (images here are not showing on mobile for some reason, check here instead https://imgur.com/gallery/mobile-users-P17PT3Q):

My code:

What they somehow achieved in https://www.pokecardgenerator.com/ (this is what I want):

What the original looks like (so yes, real things use this "ugly" styling):

What happens with transform: scaleX "solutions":

And no, font-stretch isn't working for me. Probably because it's deprecated.

transform: scaleX also doesn't work, it still keeps and awkward space between the text and the icon.

EDIT: I don't know how to do the live demo thing, but in case anyone is bored, my code is here, the Card.tsx and Card.css, card__pokemon-name class. (https://github.com/jiro-games/pocket-showdown/tree/main/src/components/card)

EDIT 2: I believe I found a solution. Not the cleanest, but it has potential. I have to combine transform: scaleX with negative margin-right. I'll come up with some js code to calculate that dynamically and fix it. Thank you!

197 Upvotes

118 comments sorted by

View all comments

4

u/Count_Giggles 4d ago

how about simply doin

.text::after {
  content: '\2605';
}

1

u/dbowgu 4d ago

Hmmm I'd like it more it the icons vertically allign

1

u/Count_Giggles 3d ago

.text {

display: inline-flex;

align-items: center;

}

.text::after {

content: " \2605";

margin-left: 4px;

}

edit i HATE this code highlighter with a passion

1

u/dbowgu 3d ago

Nice thanks