Search code examples
htmlcsscentering

Having text center and aligned on the page no matter what the size of the browser is


I am using the tag <h1> in HTML and I'm trying to put the text in the middle of the webpage, no matter how much you change the size of the webpage. Basically so the text is responsive to the size of the webpage as well. Here is what I mean:

In my css page, I tried to do the following:

h1 {
 text-align: center;
 display: table-cell;
 vertical-align: middle;
}

However, this didn't work. How would I do this?


Solution

  • You can do that multiple ways, two common ones are with the positioning and Flexbox:

    Positioning:

    body {
      position: relative; /* usually the parent, in this case the body element, has position relative so that the absolute positioned child is positioned relative to it */
      height: 100vh; /* 100% of the viewport height */
      margin: 0; /* recommended */
    }
    
    h1 {
     position: absolute; /* taken out of the normal flow of the document */
     top: 50%; /* moved down by 50% of the screen height */
     transform: translateY(-50%); /* moved back up (Y axis) by half of its height to achieve the perfect center */
     width: 100%; /* needs to be defined to keep the default block behavior */
     text-align: center;
     margin: 0; /* again, for perfect center */
    }
    <h1>This is center aligned text</h1>

    Flexbox:

    body { /* or any other parent element */
      display: flex; /* flex behavior (displays children inline) */
      justify-content: center; /* horizontal centering */
      align-items: center; /* vertical centering */
      height: 100vh;
      margin: 0;
    }
    
    h1 {
      text-align: center; /* comes in handy when resizing the browser width, if the text is long/big enough */
    }
    <h1>This is center aligned text</h1>