【问题标题】:Width of elements in flex container depends on content in last elementflex 容器中元素的宽度取决于最后一个元素中的内容
【发布时间】:2019-11-12 23:17:59
【问题描述】:

我有包含 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;
  }
}


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

【问题讨论】:

  • 你的意思是说样式应该应用到前两行而不是第三行吧?
  • 我的意思是如果第三个单元格不为空,则每个元素的宽度应为 33%(弹性:1)。如果第三个元素为空,则第一个单元格应为 40%(flex:1),第二个单元格应为 60%(flex:2)
  • CSS AFAIK 不可能。你需要 JS。

标签: html css sass flexbox


【解决方案1】:

您可以使用:empty 伪类和max-width 规则:

.row-cell {
  flex: 1;

  &:nth-child(1) {
    max-width: 40%;
  }

  &:nth-child(3):empty {
    max-width: 0;
  }
}

在 css 中转换 sass 我们可以有第三个有内容的孩子...

.row-container{
  display: flex;
}

.row-cell{
  flex: 1;
}

.row-cell:nth-child(1){
  max-width: 40%;
}

.row-cell:nth-child(3):empty{
  max-width: 0;
}
<div class="row-container">
  <div class="row-cell" style="background-color:#ff0000">
    <div class="content">
      <h1>Some content 1</h1>
    </div>
  </div>
  <div class="row-cell" style="background-color:#00ff00">
    <div class="content">
      <h1>Some content 2</h1>
    </div>
  </div>
  <div class="row-cell" style="background-color:#0000ff">
    <div class="content">
      <h1>Some content 3</h1>
    </div>
  </div>
</div>

...或没有任何内容:

.row-container{
  display: flex;
}

.row-cell{
  flex: 1;
}

.row-cell:nth-child(1){
  max-width: 40%;
}

.row-cell:nth-child(3):empty{
  max-width: 0;
}
<div class="row-container">
  <div class="row-cell" style="background-color:#ff0000">
    <div class="content">
      <h1>Some content 1</h1>
    </div>
  </div>
  <div class="row-cell" style="background-color:#00ff00">
    <div class="content">
      <h1>Some content 2</h1>
    </div>
  </div>
  <div class="row-cell" style="background-color:#0000ff"></div>
</div>

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 是的,如果缺少第三个元素,这可以工作,但在我的情况下,有第三个元素,但没有任何内容。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-10
    • 1970-01-01
    • 2020-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-14
    相关资源
    最近更新 更多