In an attempt to adjust the width of a span dynamically based on its content, I am facing a challenge. My application consists of multiple spans in rows and users can modify the content of these spans. To ensure uniformity in span width after content changes, I aim to set each span's width equal to the maximum width among all spans.
For instance:
spanWidths = [ '50px', '34px', '56px', '87px' ]
The desired conversion of these spans would be:
[ '87px', '87px', '87px', '87px' ]
https://i.sstatic.net/hXLKj.png
When inspecting the box model for the span:
https://i.sstatic.net/twno1.png
Despite setting the width to 87px
on the span, inspection shows a strange value like 57.98px
due to border, padding, and content considerations.
The CSS style for the span is as follows (with consistent use of box-sizing: border-box
):
.annotation-speaker {
display: inline-block;
font-size: 14px;
line-height: 25px;
background-color: rgb(224, 239, 241, 0.5);
height: 25px;
padding: 0px 5px 6px 5px;
margin-top: 5px;
border-radius: 4px;
font-weight: 500;
letter-spacing: 0.7px;
overflow: hidden;
text-align: center;
}
I am uncertain about how to calculate the spanWidths
array with updated widths after modifying span content.
This is my current approach:
const css = getComputedStyle($speakerBox); // $speakerBox refers to the span
const r = $speakerBox.getBoundingClientRect();
const w = $speakerBox.scrollWidth + parseInt(css.paddingLeft) + parseInt(css.paddingRight);
maxSpeakerTagWidth = Math.max(maxSpeakerTagWidth, w);
Both r.width
and $speakerBox.scrollWidth
provide different values, leaving me confused about which one to prioritize.
To set all spans to the same width as maxSpeakerTagWidth
:
$speakerBox.style.width = maxSpeakerTagWidth + 'px';
However, this solution doesn't seem to work as expected!