Vertical Align Methods

后端 未结 5 1564
长发绾君心
长发绾君心 2020-12-21 04:52

What are the best methods to vertically-align something relative to it\'s elements dimensions. As of right now, I\'m only aware of vertical-align:middle;<

5条回答
  •  臣服心动
    2020-12-21 05:06

    Here are 3 very good techniques for vertically centering a child within a container - even when you don't know the height of the child element. The first 2 come from this CSS-tricks article

    Markup (for all methods):

    Some text

    Solution #1: CSS tables method (FIDDLE)

    CSS:

    /* This parent can be any width and height */
    .block {
      display: table;
       width: 100%;
       background: orange;
       height: 300px;
    }
    
    
    .centered {
       display: table-cell;
       text-align: center;
       vertical-align: middle;
       background: pink;
    }
    

    Solution #2: Pseudo ('Ghost') element method (FIDDLE)

    CSS:

    /* This parent can be any width and height */
    .block {
      text-align: center;
      background: orange;
      height: 300px;
    
    }
    
    /* The ghost, nudged to maintain perfect centering */
    .block:before {
      content: '';
      display: inline-block;
      height: 100%;
      vertical-align: middle;
      margin-right: -0.25em; /* Adjusts for spacing */
    }
    
    /* The element to be centered, can
       also be of any width and height */ 
    .centered {
      display: inline-block;
      vertical-align: middle;
      width: 300px;
        background: pink;
    }
    

    Solution #3: Flexbox (FIDDLE)

    (Relevant) CSS:

    .block {
       background: orange;
       height: 300px;
       display: flex;
       align-items: center;
    }
    

提交回复
热议问题