Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

css: How to horizontal align fonts with different sizes

first question on SO !

Im trying to "pixel perfect" horizontal align two lines of text , each line with a different font-size.

<style type="text/css">
    *   { font-family: sans-serif;}
    div { float: left;}
    h1  { font-size: 150px;  margin-bottom:-30px; }
</style>

        <div>
            <h1> B </h1>
            <h6> B-L.align </h6>
        </div>
        <div>
            <h1> L </h1>
            <h6> L.align </h6>
        </div>

sample here: http://jsfiddle.net/jgYBD/1/

If you look at the sample , you will notice that the larger font has more "?padding?" than the smaller font. making them misaligned by a few pixels.

Im looking for a way or formula to perfectly left align them ,without using trial and error on the margin-left!

All ideas are appreciated , thanks.

like image 639
andsoa Avatar asked Feb 06 '13 16:02

andsoa


People also ask

How do I arrange text horizontally in CSS?

The text-align property is used to set the horizontal alignment of a text. A text can be left or right aligned, centered, or justified.

How do I align text horizontally?

To align text horizontally on a page, highlight the text you want to center. Next, click the “Center Alignment” icon in the “Paragraph” group of the “Home” tab. Alternatively, you can use the Ctrl+E keyboard shortcut. Your text will now be horizontally aligned.

How do I align fonts?

Select the text that you want to align. On the Home tab, in the Paragraph group, click Align Left or Align Right .


2 Answers

What you are seeing is not padding, but some kind of "kerning" of the font. Not really that, but sort of. The big big problem about that is that it is different for every font, and even for every letter. try replacing the

<h1>B</h1>

by

<h1>J</h1>

now the space is much smaller !

this space depends of the font, the size and the letter. So, I don't think that you can control that

like image 72
vals Avatar answered Sep 21 '22 09:09

vals


A potential trick: Add :first-letter { margin-left: -0.08em; }. The em has to be adjusted for your font, but you can apply it globally if you want. It does result in a small shift to the left, but you can change the font-size of the H1 with impunity and it stays aligned.

See this update to your jsFiddle.

It doesn't fix the "J" issue though so it might be a moot point for you.

like image 27
davemyron Avatar answered Sep 21 '22 09:09

davemyron