Search code examples
htmlcsscss-grid

How to remove gap for CSS Grid with height: 0 element


I recently started to use CSS grid. I need to set an empty div element as one of the grid elements so that I can insert contents by javascript when needed. The problem is that gap is applied to this element which is empty and height: 0. How can I avoid to apply gap only when the element is empty for CSS grid.

<div class="container"> <!-- gap: 20px; -->
    <div class="grid-element--1">
        <h2>title</h2>
        <p>Text Text Text Text Text Text Text Text Text Text </p>
    </div>
    <div class="grid-element--2">
        <h2>title</h2>
        <p>Text Text Text Text Text Text Text Text Text Text </p>
    </div>
    
    <div class="grid-element--3"></div> <!-- Need to appliy gap: 20px only when this element is not empty -->
    
    <div class="grid-element--4">
        <h2>title</h2>
        <p>Text Text Text Text Text Text Text Text Text Text </p>
    </div>
</div>

enter image description here


Solution

  • The gap property is applied to the container. You can not set a specific gap for the children div, because it is a property of its parent.

    What I would advise is to set your empty div, with the display:none property. And once you inject content to it with javascript, set its display to "block", "flex", or whatever display property it is using when visible.

    Another solution would be to replace "gap" with margin or padding bottom on the children. And since this is a property of the children components, you will be able to make individual exceptions.