繁体   English   中英

flex 容器中元素的宽度取决于最后一个元素中的内容

[英]Width of elements in flex container depends on content in last element

我有行容器,其中包含 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;
  }
}


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

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

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

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

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

  &:nth-child(3) {
    flex: 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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM