Flexbox vertical align specific content within a w

2019-07-04 04:14发布

My CMS has a rather rigid setup with 2 columns with headers and content, as below:

.wrapper {
    overflow: auto;
    border: 1px solid #ccc;
    text-align: center;
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;
    -ms-flex-align: center;
    -webkit-align-items: center;
    -webkit-box-align: center;
    align-items: center;
}
.left,
.right {
    float: left;
    width: 45%;
    padding: 5px;
}
<div class="wrapper">
    <div class="left">
        <h3>Title (should be aligned to top)</h3>
        <div class="content">
            left<br>
            left<br>
            left<br>
            left<br>
        </div>
    </div>
    <div class="right">
        <h3>Title (should be aligned to top)</h3>
        <div class="content">
            right
        </div>
    </div>
</div>


jsFiddle


I want to make the .content of each column align vertically to the middle but keep the header h3s vertically aligned to the top.

Normally I would achieve vertical align using flexbox as such:

.wrapper {
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;
    -ms-flex-align: center;
    -webkit-align-items: center;
    -webkit-box-align: center;
    align-items: center;
}

but of course this affects all elements within .wrapper.

Would anyone know a way I could 'target' the .content classes and get the same effect (keeping in mind I cannot really alter the HTML)?

2条回答
爷、活的狠高调
2楼-- · 2019-07-04 04:47

check this fiddle

.wrapper {
    overflow: auto;
    border: 1px solid #ccc;
    text-align: center;
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;
    -ms-flex-align: flex-start;
    -webkit-align-items: flex-start;
    -webkit-box-align: flex-start;
    align-items: flex-start; // changed
}
查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-07-04 04:52

This is a sort of a hack, but it works:

  1. Remove align-items: center from the wrapper and flex:1 to the flex children left and right

  2. Make the inner left and right container a column flexbox and center the h3 and content using justify-content:center

  3. Use margin-bottom:auto to push both h3 to the top and allow content to stay at the middle.

See demo below:

.wrapper {
  overflow: auto;
  border: 1px solid #ccc;
  text-align: center;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
}
.left,
.right {
    padding: 5px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    flex: 1;
}
.left h3, .right h3 {
    margin-bottom: auto;
}
.content {
    margin-bottom: auto;
}
<div class="wrapper">

  <div class="left">
    <h3>
    Title (should be aligned to top)
    </h3>
    <div class="content">
      left
      <br>left
      <br>left
      <br>left
      <br>
    </div>
  </div>

  <div class="right">
    <h3>
  Title (should be aligned to top)
  </h3>
    <div class="content">
      right
    </div>
  </div>

</div>

查看更多
登录 后发表回答