javascripthtmlcss

Have multiple elements with different parents have same width as widest


Note that for items in a list or with otherwise the same parent there are existing questions such as this one - However they don't cover what I'm asking as they all deal with items in a table, grid, or otherwise sharing a parent.

I have multiple buttons on my page and due to some frankly boneheaded design decisions made 20 years ago they're all in different containers that I can't touch.

Example:

<button class="myButton">really long text means really wide button</button>
<!-- elsewhere, under a different parent -->
<button class="myButton">small button</button>
<!-- even further away parented to yet another element -->
<button class="myButton">kinda medium text</button>

How can I, in either CSS or plain JavaScript, make all of the buttons the width of the widest one, without caring about where they are on the page? The number of buttons varies but is thankfully determined before the page is rendered, and the text is known ahead of time (e.g. the widest button will always say "really long text means really wide button").


Solution

  • Here's a simple JS approach that could be used for initialising a handful of elements to the same size. It won't handle dynamic content, but should show the process you'd need for handling this in JS.

    // Find all the relevant elements
    const buttons = document.getElementsByClassName('myButton')
    // Find the largest width among those elements
    // getElementsByClassName returns a HTMLCollection, spreading that into an array allows us to use reduce()
    const maxWidth = [...buttons]
      .reduce((max, current) =>
        // Check each element and if it has a larger width, update the maximum
        Math.max(max, current.getBoundingClientRect().width),
        // Start with a max width of 0
        0
      )
    
    // Update the width of each button to the maxium width we just found
    for (let btn of buttons) {
      btn.style.width = `${maxWidth}px`
    }
    <button class="myButton">really long text means really wide button</button>
    <!-- elsewhere, under a different parent -->
    <button class="myButton">small button</button>
    <!-- even further away parented to yet another element -->
    <button class="myButton">kinda medium text</button>