Why does the text break like that although there is enough space?!

Why does the text in the below H2 tag break into two lines although there is enough space?
Note: if you have a large screen, try to shrink the browser to see the problem.

<div>
    <h1>This is how you do it</h1>
</div> 
* {
        padding: 0;
        margin: 0;
      }
      div {
        position: relative;
        background: #29a2e2;
        height: 100vh;
      }
      h1 {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%,-50%);
        font-family: montserrat;
        font-size: 4em;
        text-transform: uppercase;
        color: white;
        text-shadow: 0px 1px #000;
      }

There is not enough space, it goes off the right edge of the page. Disable the transform and you will see it.

You are right. But why that happens?

Because the text is rendered in the absolute position that you give it, then the transform relocates it after that.
Try something like this:

h1 {
        position: relative;
        text-align: center;
        top: 50%;
        margin-top: -0.5em;
        font-family: montserrat;
        font-size: 4em;
        text-transform: uppercase;
        color: white;
        text-shadow: 0px 1px #000;
      }

Though the negative margin is a bit of a hack, but it works better than transform.

It doesn’t really work. The div’s height now isn’t 100% of the viewport.

@SamA74 I have just found a solution. Thank you.

div {
        display: table;
        background: #29a2e2;
        height: 100vh;
        width: 100%;
      }
      h1 {
        display: table-cell;
        text-align: center;
        vertical-align: middle;
        font-family: montserrat;
        font-size: 4em;
        text-transform: uppercase;
        color: white;
        text-shadow: 0px 1px #000;
      }

Didn’t spot that, had Inspect element on, so missed the bottom.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.