Is it possible to collapse a css grid column if the contents are empty

Viewed 23

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 class="button">OK</div>
  <div class="button">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 at this codepen

So, we can see if the OK text is long, then the Cancel button also grows to the same width

enter image description here

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

eg

<div id="container">
  <div class="button">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?

2 Answers

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 class="button">Close</div>
</div>

Related