Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perfectly vertical align top of fonts of 2 different text sizes using CSS

Tags:

html

css

I want to achieve this design: example

Note that both text are perfectly top aligned but I'm almost sure this is impossible to achieve in CSS in a scalable way (I mean not hardcoding pixels with position relative/top for example).

Using flex looked like a good way to achieve this but since this is text, the top alignment is correct but based on the text 'bounding box' but the letters '77' don't take up 100% height of that box, causing it to not be perfectly aligned.

I understand why this happens since letter 'a' doesn't take up the same space as letter 'X' but I was just wondering if someone can find out a very nice tricky to achieve this design.

Here are my two attempts at this:

div#a {
  
  background:#EEE;
  line-height: 1;
}


span {
  vertical-align: text-top;
}

#b {
  display: flex;
  align-items: flex-start;
}

 
 <div id="a">
        <span style=" font-size: 48px;">77</span>
        <span style="font-size:14px;;">USD</span>
    </div>

<div id="b">
  <div style=" font-size: 48px; line-height: 48px;">77</div>
  <div style=" font-size: 14px;">USD</div>
</div>

(please note there is a related issue but they didn't want 'perfect' alignment like this)

like image 639
AlfaTeK Avatar asked Mar 13 '19 01:03

AlfaTeK


1 Answers

I think you can use this approach and tuning the line-height property.

div {
  display: flex;
  flex-flow: row nowrap;
  align-items: flex-start;
  margin-bottom: 10px;
}

div .container span {
  line-height: 60%;
}
<div id="a">
  <div class="container">
    <span style=" font-size: 48px;">77</span>
  </div>
  <div class="container">
    <span style="font-size:14px;">USD</span>
  </div>
</div>

<div id="b">
  <div class="container">
    <span style=" font-size: 48px;">100</span>
  </div>
  <div class="container">
    <span style="font-size:14px;">USD</span>
  </div>
</div>
like image 140
Pablo Darde Avatar answered Oct 07 '22 14:10

Pablo Darde