2
votes

Suppose, I have two div's: first - rectangle, filled yellow color and second with text "World wide web" and font-size 46px. I need set distance 39px between bottom of first div and top of the capital letter "W" in second div. I set margin bottom 39px in first div's CSS rule, and measure result on the screen. I got 43px. Can I exactly set this distance? (of cource, I can tune margin of first div and make several attempts to set this distance, but I need another way). Sorry for my English.

<!doctype html>

<html>
  <head>
    <title>
      test page
    </title>
    <style>
      html {
        line-height: 1;
      }
      #first {
        background-color: yellow;
        height: 200px;
        margin-bottom: 39px;
        width: 200px;  

      }

      #second {
        font-family: "Myriad Pro";
        font-size: 46px;
      }
    </style>
  </head>
  <body>
    <div id = "first">
     </div>
    <div id = "second">
      World wide web
    </div>
  </body>
</html>

screenshot

2
Check default browser styles that are being applied. Using something like normalize.css sometimes takes the guesswork out of why something is behaving this way or that way. Etc etc - feitla
I think, this is because font-size bigger than height of capital letter.... - igor_rb
I include normalize.css and got the same result: 43px. - igor_rb
Your idea is correct: the X-height is not the same as the font size. You could compute what the X-height is, but I say, don't bother. Not all computers have the font Myriad Pro, so it will come out differently anyway! - Mr Lister

2 Answers

2
votes

You might need to set the padding of the text in the second div to {padding: 0}. Any padding that you have not accounted for will increase the appearance of the margin. Have you tried adding a background-color to #second and then measuring the margin?

1
votes

I think that the space is part of the font. The size of second div, font-size and line-height all are 46px. Also, the space between them is also 39px as you can see here. So, if you want to set the space to be exactly 39px, you might have to search for or make a font which doesn't has that extra space.

OR

you can set line-height: 30px; in second div, which will move it upward. But as value depends on font-size, you will have to change it whenever you change font-size. Maybe using ems can solve that issue

EDIT

Values in em would be:

font-size: 2.87em;
line-height: 0.655em;

Now changing font-size in em to any value will keep the gap to 39px, i.e. margin-bottom of div#first

DEMO