-1

How can I align this text vertically in the middle of the divs?
I've already tried to change the position using relative/absolute, and changing the top and left of the paragraph, but it doesn't work at all.

 div.roxo{
      background-color: purple;
      padding: 40px;
    }
    div.amarelo{
      background-color: yellow;
      height: 300px;
      width: 25%;
      float: left;
    }
    div.vermelho{
      background-color: red;
      height: 300px;
      width: 50%;
      float: left;
    }
    div.verde{
      background-color: green;
      height: 300px;
      width: 25%;
      float: left;
    }
    div.azul{
      background-color: blue;
      padding: 40px;
    }
    p{
       margin: 0;
       text-align: center;
       vertical-align: middle;
    }
<!DOCTYPE html>
   <html>
    <head>
    <title>Page Title</title>
   
    </head>
    <body>
      <div class="roxo">
       <p>roxo</p>
      </div>
      <div class="amarelo">
       <p>amarelo</p>
      </div>
      <div class="vermelho">
       <p>vermelho</p>
      </div>
      <div class="verde">
       <p>verde</p>
      </div>
      <div class="azul">
       <p>azul</p>
      </div>
    </body>
   </html>
SherylHohman
  • 16,580
  • 17
  • 88
  • 94
Pankwood
  • 1,799
  • 5
  • 24
  • 43

1 Answers1

-1

You can do it using flexbox.

div.roxo{
      background-color: purple;
      padding: 40px;
    }
    div.amarelo{
      display:flex;
       justify-content:center;
      align-items:center;
      background-color: yellow;
      height: 300px;
      width: 25%;
      float: left;
    }
    div.vermelho{
      display:flex;
       justify-content:center;
      align-items:center;
      background-color: red;
      height: 300px;
      width: 50%;
      float: left;
    }
    div.verde{
      display:flex;
       justify-content:center;
      align-items:center;
      background-color: green;
      height: 300px;
      width: 25%;
      float: left;
    }
    div.azul{
      display:flex;
       justify-content:center;
      align-items:center;
      background-color: blue;
      padding: 40px;
    }
    p{
       margin: 0;
       text-align: center;
       vertical-align: middle;
    }
<!DOCTYPE html>
  <html>
    <head>
    <title>Page Title</title>
   
    </head>
    <body>
      <div class="roxo">
       <p>roxo</p>
      </div>
      <div class="amarelo">
       <p>amarelo</p>
      </div>
      <div class="vermelho">
       <p>vermelho</p>
      </div>
      <div class="verde">
       <p>verde</p>
      </div>
      <div class="azul">
       <p>azul</p>
      </div>
    </body>
  </html>

Just add:

display:flex;
justify-content:center;
align-items:center;

to your div CSS.
You can learn more about flexbox here at https://css-tricks.com/snippets/css/a-guide-to-flexbox/

SherylHohman
  • 16,580
  • 17
  • 88
  • 94
indefinite
  • 383
  • 1
  • 5
  • 18