Home > Enterprise >  How to set the width of all HTML elements to the width of the widest element in the list?
How to set the width of all HTML elements to the width of the widest element in the list?

Time:11-17

Here is my structure:

<div >
    <div >
        <span >St</span>
        <button >click</button>
    </div>
    <div >
        <span >Middletext</span>
        <button >click</button>
    </div>
    <div >
        <span >This line contains a long text.</span>
        <button >click</button>
    </div>
</div>

So, this code creates three lines of text, short, middle and long.

Naturally, width of each item-title element is equal to the length of text, so, first item-title element will have the smallest width, second one will have larger and the last one the largest width.

What I need to do in CSS is to set the width of all item-title elements to the width of the longest item-title element. I need this so that I can align all item-button elements to the same horizontal position.

Sure, I can hardcode the width property of all item-title elements, but I really need this width to be dynamic since in reality I do not have such static list of items. I use Vue to generate those list items based on the variable values that can change.

So, how can I say to HTML: "Align all buttons next to the end of the longest line of text, please"?

CodePudding user response:

There are several ways for achieving this, the easiest is probably a table

.list
{
  display: table;
}

.list-item {
  display: table-row;
 }
 
 .item-title, .item-button {
  display: table-cell;
}
<div >
    <div >
        <span >St</span>
        <button >click</button>
    </div>
    <div >
        <span >Middletext</span>
        <button >click</button>
    </div>
    <div >
        <span >This line contains a long text.</span>
        <button >click</button>
    </div>
</div>

CodePudding user response:

Here's a flexbox approach:

.list {
  max-width: fit-content;
}

.list-item {
  white-space: nowrap;
  display: flex;
}

.item-title {
  display: inline-block;
  flex-grow: 1;
}
<div >
  <div >
    <span >St</span>
    <button >click</button>
  </div>
  <div >
    <span >Middletext</span>
    <button >click</button>
  </div>
  <div >
    <span >This line contains a long text.</span>
    <button >click</button>
  </div>
</div>

  • Related