Home > Software design >  Hide CSS Grid element if empty
Hide CSS Grid element if empty

Time:10-03

I'm trying to hide the Grid element if it is empty with the :empty pseudo-class.

CSS

.o-grid {
    display: grid;
}

.o-grid--half {
    width: 50%;
    grid-template-columns: repeat(1,minmax(0,1fr));
}

.o-grid:empty { display: none; }

Normal element with content.

<div >
    <div>Content</div>
    <div>Some Content</div>
</div>

But, if the element has no content, the Grid element space is preserved, and the browser will keep a space for it, and I want to disable this.

<div >

</div>

enter image description here

CodePudding user response:

Use the :has() selector

.o-grid {
    display: grid;
}

.o-grid--half {
    width: 50%;
    grid-template-columns: repeat(1,minmax(0,1fr));
}

.o-grid:not(:has(*)) { display: none; }
<div >
    <div>Content</div>
    <div>Some Content</div>
</div>

<div >

</div>

  • Related