Setting the width of 2 elements based on longest text

I am trying to determine the best way to make 2 elements the same size based on the text of the larger element.

German Text - same size

French Text example 2 different sizes

Basically take the 2 text items "ouverture de session" and "xyz" (used for a short word example) so that both buttons are the same size and are large enough to handle the larger of the 2 text inputs.

This can be done via Javascript, Angular, whatever.

Upvotes: 0

Views: 335

Answers (3)

parktomatomi
parktomatomi

Reputation: 4079

You can do it with CSS grids:

.button-panel {
  display: inline-grid;
  grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
  column-gap: 10px;
}
<div class="button-panel">
  <button>A very long button name</button>
  <button>Ok</button>
</div>

Upvotes: 1

Spectric
Spectric

Reputation: 31992

You can get the button with the bigger offsetWidth, then apply that to the other button's width style property.

const buttons = document.querySelectorAll('button')

if (buttons[1].offsetWidth > buttons[0].offsetWidth) {
  buttons[0].style.width = buttons[1].offsetWidth + 'px';
} else {
  buttons[1].style.width = buttons[0].offsetWidth + 'px';
}
<button>Hello World!</button>
<button>Spectric</button>

If you have ultiple buttons, a more scalable solution:

const buttons = document.querySelectorAll('button')

const biggestWidth = [...buttons].reduce((a,b) => a = b.offsetWidth > a ? b.offsetWidth + 1 : a, 0)

buttons.forEach(e => e.style.width = biggestWidth + 'px')
<button>Hello World!</button>
<button>Spectric</button>

Upvotes: 1

Harkirat Singh Virdi
Harkirat Singh Virdi

Reputation: 46

You can set the property of min-width on to the button element. By doing this the smaller button will be of same width as the larger one.

Upvotes: 0

Related Questions