CSS grid auto expand

Viewed 154

I created a 12 column grid using the CSS grid. However, now I'm stuck with auto width (Auto expand until the end) class. Can anyone tell me is there any way or workaround to achieve it?

.box {background-color: #20262e; color: #fff; padding: 2rem;}

.row {
  display: grid;
  grid-gap: 1rem;
  grid-template-columns: repeat(12, 1fr);
}

.col-6 {
    grid-column-end: span 6;
}

.col-2 {
    grid-column-end: span 2;
}

.col {
  background-color: red !important;
    /*  ??? */
}
<div class="row">
  <div class="box col-6">Parent A</div>
  <div class="box col-6">
    <div class="row">
      <div class="box col-6">Child A</div>
      <div class="box col-6">Child B</div>
    </div>
  </div>

  <div class="box col-2">A</div>
  <div class="box col">AUTO FILL</div>
  <div class="box col-2">B</div>
</div>

1 Answers

As @Temani Afif said in comments - this is a work for flex.

Using fixed span, like col-8

.box {background-color: #20262e; color: #fff; padding: 2rem;}

.row {
  display: grid;
  grid-gap: 1rem;
  grid-template-columns: repeat(12, 1fr);
}

.col-6 {
    grid-column-end: span 6;
}

.col-2 {
    grid-column-end: span 2;
}

.col-8 {
  background-color: red !important;
  grid-column-end: span 8;
}
<div class="row">
  <div class="box col-6">Parent A</div>
  <div class="box col-6">
    <div class="row">
      <div class="box col-6">Child A</div>
      <div class="box col-6">Child B</div>
    </div>
  </div>

  <div class="box col-2">A</div>
  <div class="box col-8">AUTO FILL</div>
  <div class="box col-2">B</div>
</div>

Using flex

Now it's like Bootstrap 4 Grid system. Used flex-grow: 1; for auto width flex element.

* {
  box-sizing: border-box;
}

.container {
  padding: 0 15px;
}

.box {
  background-color: #20262e;
  background-clip: content-box;
  color: #fff;
  min-height: 100px;
  padding: 0 15px 30px 15px;
}

.row {
  display: flex;
  flex-wrap: wrap;
  margin-right: -15px;
  margin-left: -15px;
}

.col-6 {
  flex: 0 0 50%;
  max-width: 50%;
}

.col-2 {
  flex: 0 0 16.66667%;
  max-width: 16.66667%;
}

.col {
  background-color: red !important;
  flex-basis: 0;
  flex-grow: 1;
  min-width: 0;
  max-width: 100%;
}
<div class="container">
  <div class="row">
    <div class="box col-6">Parent A</div>
    <div class="box col-6">
      <div class="row">
        <div class="box col-6">Child A</div>
        <div class="box col-6">Child B</div>
      </div>
    </div>

    <div class="box col-2">A</div>
    <div class="box col">AUTO FILL</div>
    <div class="box col-2">B</div>
  </div>
</div>

Related