Home > Back-end >  Is it possible to collapse a css grid column if the contents are empty
Is it possible to collapse a css grid column if the contents are empty

Time:09-21

I have a component with an OK/Cancel button, where I want the buttons both the same width regardless of the text size (eg different cultures)

So, a simplified mockup which is close to what I have is...

<div id="container">
  <div >OK</div>
  <div >Cancel</div>
</div>

#container {
  background: green;  
  right: 0;
  position: absolute;
  display: grid;
  grid-template-columns: 1fr minmax(0, 1fr)
}

.button {
  text-align: center;
  padding: 5px;
  min-width: 40px;
  width: auto;
  margin: 5px;
  background: yellow;
}

Can also see enter image description here

However, the component I am using (3rd party) also used the OK for just close

eg

<div id="container">
  <div >Close</div>  
</div>

and now I have an unwanted gap on the right hand side

enter image description here

I can target the component classes, but not the structure.

So, is there any way via just CSS I can have this grid to act like a grid-template-columns: 1fr 0 if the second div is not there?

CodePudding user response:

You may check if the span is the :only-child and make it span both columns

#container {
  background: green;
  right: 0;
  position: absolute;
  display: grid;
  grid-template-columns: 1fr minmax(0, 1fr)
}

.button {
  text-align: center;
  padding: 5px;
  min-width: 40px;
  width: auto;
  margin: 5px;
  background: yellow;
}

.button:only-child {
  grid-column: span 2;
}
<p>Test :only-child</p>
<div id="container">
  <div >Close</div>
</div>

CodePudding user response:

You can use the 'auto' value like this:

#container {
 background: green;  
 right: 0;
 position: absolute;
 display: grid;
 grid-template-columns: auto minmax(0, 1fr)
}

you can find more info here: https://developer.mozilla.org/en-US/docs/Web/CSS/grid-auto-columns

  • Related