web-dev-qa-db-ja.com

最後の行のアイテムがCSSグリッドの残りのスペースを消費するようにするにはどうすればよいですか?

グリッドの最後の行にあるすべてのアイテムを、それらがいくつあっても、強制的に行を埋める方法はありますか?

グリッドに配置するアイテムの数がわからないため、直接ターゲットにすることはできません。 grid-auto-flow: denseを使用しようとしましたが、実際には役に立ちません。

これは私の質問を視覚化したものです enter image description here

div {
  margin:20px auto;
  width: 400px;
  background: #d8d8d8;
  display: grid;
  grid-gap: 10px;
  grid-template-columns: repeat(3, 1fr);
}
span {
  height: 50px;
  background: blue;
}
<div>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>  
</div>
 
12
Ogdila

これは、CSSルールnth-childとnth-last-of-typeを組み合わせることにより、CSSグリッドで完全に可能です。唯一の注意点は、列の数を事前に知る必要があることです。

.grid {
    display: grid;
    grid-template-columns: auto auto auto;
    justify-items: start;
    grid-gap: 10px;
}

.grid div {
  border: 1px solid #ccc;
  width: 100%;
}

.grid > *:nth-child(3n-1) {
  justify-self: center;
  text-align: center;
}

.grid > *:nth-child(3n) {
  justify-self: end;
  text-align: right;
}

.grid > *:nth-child(3n-1):nth-last-of-type(1) {
  border-color: red;
  grid-column: span 2;
}

.grid > *:nth-child(3n-2):nth-last-of-type(1) {
  border-color: red;
  grid-column: span 3;
}
<div class="grid">
  <div>text</div>
  <div>TEXT</div>
  <div>text</div>
  <div>text</div>
  <div>TEXT</div>
  <div>text</div>
  <div>text</div>
  <div>TEXT</div>
</div>
0
rainecc

私はあなたの質問への答えを見つけました私はここでそれを再現しました: https://jsfiddle.net/nmcobalt/dg3mutwv/13/

モジュロ関数と3つの列の定数係数に基づいて子を計算する(sassを使用した)反復を通じて、CSSセレクターnth:last-childを使用する必要があります。

@mixin setLastChildFluid{
  @for $i from 1 through 10 {    
    $span: 3;
    @if $i % 3 == 0{
      $span: 1;
    } @else if $i % 3 == 1{
      $span: 3;
    } @else if $i % 3 == 2{
      $span: 2;
    } 
    @if $span == 2 {
      span:nth-child(#{$i - 1}){
        &:nth-last-child(2){
          grid-column-end:span 1;
          position:relative;
          bottom:0;
          width:calc(150% + 5px);
          left:0;    
        }
      }
      span:nth-child(#{$i}){
        &:nth-last-child(1){
          grid-column-start:2;
          position:relative;
          bottom:0;
          width:calc(150% + 5px);
          left:calc(50% + 5px);
        }
      }

    } @else {
      span:nth-child(#{$i}){
        &:last-child{
            grid-column-end:span #{$span};          
        }
      }
    }

  }
}
div {
  position:relative;
  margin:20px auto;
  width: 400px;
  background: #d8d8d8;
  display: grid;
  grid-gap: 10px;
  grid-template-columns: repeat(3, 1fr);

  @include setLastChildFluid;
}
span {
  height: 50px;
  background: blue;
  color:yellow;
}

そして次のhtmlマークアップ。クエリを再現するために、2つの異なる例(divでラップ)を作成しました。

<div>
  <span>1</span>
  <span>2</span>
  <span>3</span>
  <span>4</span>
  <span>5</span>
  <span>6</span>
  <span>7</span>
  <span>8</span>
</div>
<div>
  <span>1</span>
  <span>2</span>
  <span>3</span>
  <span>4</span>
  <span>5</span>
  <span>6</span>
  <span>7</span>
</div>

流体の結果を確認するには、divの数を変更します。