Search code examples
htmlcssangularalignmentboilerplate

How to align a paragraph in the middle of the div?


Using a couple of Angular containers I want to align in the middle of the cells the text. Unfortunately the vertical align doesn't work.

Hereby the code:

main {
  height: 100%;
  text-align: center;
  padding-top: 6%;
  padding-left: 7%;
  padding-right: 7%;
  font-size: 1em;
}

.vertical-align {
  height: 100%;
}

p {
  position: relative;
  vertical-align: middle;
}
<main>
  <div class="vertical-align">
    <p>{{ data.text}}</p>
  </div>
</main>

Do you have any idea how I could fix this?

Thank you!


Solution

  • Vertical align doesn't work with block elements. p tag is a block element

    In order to center vertically you need to use flexbox

    .vertical-align {
      height: 100%;
      display:flex;
      align-items:center;
    }
    

    Refer example below, Also not that I changed the height of the main container from 100% to 100vh just for the sake of the example

    main {
      height: 100vh;/*for example purpose*/
      text-align: center;
      padding-top: 6%;
      padding-left: 7%;
      padding-right: 7%;
      font-size: 1em;
    }
    
    .vertical-align {
      height: 100%;
      display:flex;
      align-items:center;
      border:1px solid red;/*for example purpose*/
    }
    
    p {
      position: relative;
      /*vertical-align: middle;*/
    }
    <main>
      <div class="vertical-align">
        <p>lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem </p>
      </div>
    </main>