0

Let's say I have a <div> element, and I want to make its width equal the current line-height. Is there a CSS unit or some fancy calc() function that will accomplish this? I know a workaround is to simply hard-code the actual line-height into a calc() function, but I want to know if there is a way that will work with all line-heights.

What I have so far, but I don't like using a hard-coded line-height value (1.33 in this example):

.test {
width: calc(1em * 1.33);
height: auto;
background-color: red;
}

<div class="test"></div>
user3163495
  • 2,425
  • 2
  • 26
  • 43
  • For as far as I know, you need to hardcode the value or use the same calc() as width. But, given your example, what if `1em` = `24px`?? Then `height: 30px` would get you in trouble as `line-height` would be 1.33 * 24 = 31.92px – Rene van der Lende Jun 08 '20 at 00:40
  • @RenevanderLende the height can be anything, I'm just focusing on the width for now. I'll remove the height: 30px as it seems to be confusing – user3163495 Jun 08 '20 at 00:42
  • what is your purpose on doing this? – Temani Afif Jun 08 '20 at 00:43
  • @TemaniAfif world domination, of course – user3163495 Jun 08 '20 at 00:43
  • Then I'd say, make it 42 – Rene van der Lende Jun 08 '20 at 00:44
  • 1
    There is currently no way do do what you want in CSS only. There is a proposal for the CS length unit `lh` which does exactly what you want, but currently no browser supports it. So, are you willing to use JavaScript? – Mr Lister Jun 08 '20 at 08:05
  • You could use 'CSS variables': `line-height: var(--some-lineheight)` and `width: var(--some-lineheight)` or alternatively `width: calc(var(--some-lineheight) * var(--multi-plication-factor))`. But 'CSS variables' are not supported by IE11. Workaround would be some fixed calc() for IE and use 'CSS variables' for the rest. Check [caniuse: 'CSS variables'](https://caniuse.com/#feat=css-variables). Need a proper answer on this? – Rene van der Lende Jun 09 '20 at 14:04
  • @MrLister I'm currently using JavaScript to accomplish this, yes – user3163495 Jun 10 '20 at 01:07
  • @RenevanderLende I'm using JavaScript to accomplish what I want, but it would be nice to have a cleaner solution, so yea a proper answer is always welcome – user3163495 Jun 10 '20 at 01:08

0 Answers0