首页 > 解决方案 > flex 容器中元素的宽度取决于最后一个元素中的内容

问题描述

我有行容器,其中包含 3 个带有内容的行单元格。第三个单元格可能为空

   <div class="row-container">
    <div class="row-cell">
      <div class="content">
        <h1>Some content 1</h1>
      </div>
    </div>
    <div class="row-cell">
      <div class="content">
        <h1>Some content 2</h1>
      </div>
    </div>
    <div class="row-cell">
      <div class="content">
        <h1>Some content 3</h1>
      </div>
    </div>
  </div>


这些元素的宽度取决于数量元素。
如果第三个单元格不为空:

  .row-cell{
   &:nth-child(1){
    flex: 1;
  }

  &:nth-child(2){
    flex: 1;
  }

   &:nth-child(3){
    flex: 1;
  }
}


如果第三个单元格为空:

 .row-cell{
   &:nth-child(1){
    flex: 1;
  }

  &:nth-child(2){
    flex: 2;
  }
}


我应该如何编写样式以使其同时工作?

标签: htmlcsssassflexbox

解决方案


您可以在nth-child(2)规则中嵌套一个额外的选择器,检查它是否也是最后一个元素。如果是,则增加弹性数。

.row-cell {
  &:nth-child(1) {
    flex: 1;
  }

  &:nth-child(2) {
    flex: 1;

    &:last-child {
        flex: 2;
    }
  }

  &:nth-child(3) {
    flex: 1;
  }
}


推荐阅读