垂直对齐文本

时间:2019-05-27 01:17:44

标签: html css alignment

我已经测试了很多解决方案,但是对我来说不起作用。如何在div的中间垂直对齐这些文本?我已经尝试过使用相对/绝对和更改段落的顶部和左侧来更改位置,但这根本不起作用。

 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>

感谢您的帮助。

谢谢

1 个答案:

答案 0 :(得分:1)

您可以使用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>

只需添加

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

在您的div CSS中。 您可以在https://css-tricks.com/snippets/css/a-guide-to-flexbox/

上查看有关flexbox的更多信息
相关问题