CSS - Break grid elements and stretch to widest in column

Viewed 125

I have two buttons in one row, one wider than the other. If the viewport gets too small, the buttons should "break", meaning they sit in one column. In that case the smaller button should stretch its width to the width of the wider button.

I have prepared a codepen which simulates my current stand point:

.outer {
  display: flex;
  justify-content: center;
}

.inner {
  display: inline-grid;
  grid-template-columns: repeat(2, minmax(min-content, max-content));
  grid-gap: 16px;
}

button {
  border: none;
  background: transparent;
  padding: 10px 48px;
}

.stroke {
  border-bottom: 2px solid black;
}

.flat {
  background: black;
  color: white;
}
<div class="outer">
  <div class="inner">
    <button class="stroke">
      <span>WIDER BUTTON</span>
    </button>
    <button class="flat">
      <span>BUTTON</span>
    </button>
  </div>
</div>

https://codepen.io/simonmeier/pen/xxOMKQg

The texts in the buttons are dynamic, meaning I don't know what's gonna be in there, so "hard-coding" a width doesn't work.

Is this possible with plain (s)css?

Thanks in advance.

2 Answers

You could use flex on your container instead of inline-grid.

Then by applying flex-wrap: wrap; the content will automatically wrap to the next line if is doesn't fit.

And putting flex-grow: 1; on the smaller button makes it so the button will grow to fit the container.

.outer {
  display: flex;
  justify-content: center;
}

.inner {
  display: flex;
  flex-wrap: wrap;
  margin: 0 -16px;
}

button {
  border: none;
  background: transparent;
  padding: 10px 48px;
  margin: 0 16px;
}

.stroke {
  border-bottom: 2px solid black;
  width: 300px;
}

.flat {
  background: black;
  color: white;
  width: 200px;
  flex-grow: 1;
}
<div class="outer">
  <div class="inner">
    <button class="stroke">
      <span>WIDER BUTTON</span>
    </button>
    <button class="flat">
      <span>BUTTON</span>
    </button>
  </div>
</div>

A solution could be use flex-wrap: wrap changing the display property to flex in .inner and flex: 1 1 auto; to your button.

If you want more control to your layout, consider using @media queries.

.outer {
    display: flex;
    justify-content: center;
}

.inner {
    /*display: inline-grid;
    grid-template-columns: repeat(2, minmax(min-content, max-content));*/
    display: flex;
    flex-wrap: wrap;
    /*grid-gap: 16px;*/
}
button {
    border: none;
    margin: 8px;
    flex: 1 1 auto;
    background: transparent;
    padding: 10px 48px;
}

.stroke {
    border-bottom: 2px solid black;
}

.flat {
    background: black;
    color: white;
}
<div class="outer">
    <div class="inner">
        <button class="stroke">
            <span>WIDER BUTTON</span>
        </button>
        <button class="flat">
            <span>BUTTON</span>
        </button>
    </div>
</div>

Related