grid-template-area : auto grid sizing on conditional event

36 views Asked by At

I'm encountering a problem auto sizing a grid element if some condition arises.

Consider the following grid:

grid-template-areas: 
    "1  2   2   2"
    "3  4   4   4"
    "5  6   7   8";

What I need is to 6 to take up the space of 7 and 8 if 7 and 8 are not present in the html which might happen.

That would make the grid template look like this one:

grid-template-areas: 
    "1  2   2   2"
    "3  4   4   4"
    "5  6   6   6";

Is there a way to do this in CSS?

The HTML code looks like this:

<div class="details-etherlns-incident">
   <div class="1">Text</div>
   <div class="2">Text</div>
                    
   <div class="3">Text</div>
   <div class="4">Text</div>
   
   <div class="5">Text</div>
   <div class="6">Text</div>
                    
<?php if (someCondition): ?>

   <div class="7">Text</div>
   <div class="8">Text</div>

<?php endif; ?>
</div>

Thanks in advance for your time and help.

1

There are 1 answers

1
Temani Afif On

You can do like below. You only need one rule applied to 3 selectors. The item 6 will be considered only if it's the last one

.details-etherlns-incident {
  display: grid;
  gap: 5px;
  margin: 20px;
}
.details-etherlns-incident :nth-child(2),
.details-etherlns-incident :nth-child(4),
.details-etherlns-incident :nth-child(6):last-child {
   grid-column: 2/span 3;
}

 

.details-etherlns-incident > * {
  border:1px solid;
  padding: 10px;
}
<div class="details-etherlns-incident">
   <div class="1">Text 1</div>
   <div class="2">Text 2</div>
                    
   <div class="3">Text 3</div>
   <div class="4">Text 4</div>
   
   <div class="5">Text 5</div>
   <div class="6">Text 6</div>
                    
   <div class="7">Text 7</div>
   <div class="8">Text 8</div>

</div>

<div class="details-etherlns-incident">
   <div class="1">Text 1</div>
   <div class="2">Text 2</div>
                    
   <div class="3">Text 3</div>
   <div class="4">Text 4</div>
   
   <div class="5">Text 5</div>
   <div class="6">Text 6</div>

</div>