flexbox vertical align child top, center another

前端 未结 2 1661
孤街浪徒
孤街浪徒 2021-01-07 08:37

I\'ve got the following markup:



        
相关标签:
2条回答
  • 2021-01-07 09:04

    No, not really, not without another wrapper which is a flex-container.

    As flexbox is, to a certain extent based on manipulting margins, there is no method (AFAIK, although I'd be interested to find out if there is) to justify-content: center and then align-self a child element to somewhere else other than center.

    I'd go with something like this: Add a wrapper to the "content" div, give it flex:1 to fill the remaining space below the header, then make that wrapper display:flex with justify-content:center.

    This seems to be the most logical method

    .col {
      height: 150px;
      width: 80%;
      margin: 1em auto;
      border: 1px solid grey;
      display: flex;
      flex-direction: column;
    }
    .header {
      background: lightblue;
    }
    .content {
      background: orange;
    }
    .flexy {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: center;
      background: plum;
    }
    <div class="col">
      <div class="header">Header #2</div>
      <div class="flexy">
        <div class="content">Lorem Ipsum
          <br />Dolor</div>
      </div>
    </div>

    Codepen Demo

    0 讨论(0)
  • 2021-01-07 09:09

    Flexbox opens up all sorts of opportunities with margin: auto; this is one of them. Setting margin to auto along the flex axis (vertical in this case) will absorb any extra space before dividing it up between the flex items. Finally it's possible to vertically center stuff without creating a div soup.

    .row {
      display: flex;
      align-items: stretch;
      
      margin: -16px;
      background: #ffffd;
    }
    
    .row .col {
      display: flex;
      flex-direction: column;
      
      flex: 1;
      
      margin: 16px;
      background: #fff;
    }
    
    .header, .content, .footer {
      padding: 16px;
      
      background: red;
    }
    
    .content {
      margin-top: auto;
      margin-bottom: auto;
    }
    <div class="row">
        <div class="col">
            <div class="header">Header #1</div>
            <div class="content">Lorem Ipsum<br />Dolor<br />Sit Amet</div>
            <div class="footer">Footer</div>
        </div>
    
        <div class="col">
            <div class="header">Header #2</div>
            <div class="content">Lorem Ipsum<br />Dolor</div>
        </div>
    </div>

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