flexbox vertical align child top, center another

偶尔善良 提交于 2019-12-02 10:22:20

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

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: #ddd;
}

.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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!