How to vertically align text inside a flexbox?

前端 未结 10 1212
不知归路
不知归路 2020-11-22 09:24

I would like to use flexbox to vertically align some content inside an

  • but not having great success.

    I\'ve checked online and many of the tut

  • 相关标签:
    10条回答
    • 2020-11-22 10:20

      Set the display in li as flex and set align-items to center.

      li {
        display: flex;
      
        /* Align items vertically */
        align-items: center;
      
        /* Align items horizontally */
        justify-content: center;
      
      }
      

      I, personally, would also target pseudo elements and use border-box (Universal selector * and pseudo elements)

      *,
      *::before,
      *::after {
        padding: 0;
        margin: 0;
        box-sizing: border-box;
      }
        
      
      0 讨论(0)
    • 2020-11-22 10:21

      You could change the ul and li displays to table and table-cell. Then, vertical-align would work for you:

      ul {
          height: 20%;
          width: 100%;
          display: table;
      }
      
      li {
          display: table-cell;
          text-align: center;
          vertical-align: middle;
          background: silver;
          width: 100%; 
      }
      

      http://codepen.io/anon/pen/pckvK

      0 讨论(0)
    • 2020-11-22 10:27

      It's depend on your li height just call one more thing line height

      * {
        padding: 0;
        margin: 0;
      }
      
      html,
      body {
        height: 100%;
      }
      
      ul {
        height: 100%;
      }
      
      li {
        display: flex;
        justify-content: center;
        align-self: center;
        background: silver;
        width: 100%;
        height:50px;line-height:50px;
      }
      <ul>
        <li>This is the text</li>
      </ul>

      0 讨论(0)
    • 2020-11-22 10:29

      * {
        padding: 0;
        margin: 0;
      }
      html, body {
        height: 100%;
      }
      ul {
        height: 100%;
      }
      li {
        display: flex;
        justify-content: center;
        align-items:center;
        background: silver;
        width: 100%;
        height: 20%;
      }
      <ul>
        <li>This is the text</li>
      </ul>

      0 讨论(0)
    提交回复
    热议问题