Home / Diary of a solo dev building a web app / Tech note: make HTML elements equal size with Svelte actions edit
Try Documentalist, my app that offers fast, offline access to 190+ programmer API docs.

I wanted to center a bunch of buttons, both vertically and horizontally. Easy enough: use flexbox and center in both directions:
<div class="flex flex-col justify-center items-center">
	<button>button 1</button>
	<button>another button</buton>
`flex flex-col justify-center items-center" is just Tailwind CSS way of saying:
.container {
	display: flex;
	flex-direction: column;
  justify-content: center; /* center on main axis */
	align-items: center; /* center of cross axis */
This has one problem: the buttons are not the same width.
I’m sure there are many ways to solve that. I came up with a way that uses Svelte actions.
An action is a function called after element is mounted as HTML node.
At that time we have access to layout information i.e. position and size of the node.
The idea: use action on each button, keep track of max element width and resize all button to have the same width of the largest button.
import { EqualSizeData, equalwidth } from "./actions/equalsize";

let eqsize = new EqualSizeData();

<div class="flex flex-col justify-center items-center">
	<button use:equalwidth={eqsize}>button 1</button>
	<button use:equalwidth={eqsize}>another button</buton>
Here’s the action:
export class EqualSizeData {
  nodes = [];
  max = 0;

export function equalwidth(node, data) {
  const r = node.getBoundingClientRect();

  if (r.width > data.max) {
    for (let n of data.nodes) {
      n.style.width = r.width + "px";
    data.max = r.width;
  } else {
    node.style.width = data.max + "px";
It’s pretty straightforward.
We share EqualSizeData among multiple elements.
use:equalwidth={eqsize} calls equalwidth function with HTML node and eqsize value.
In equalwidth we get the width of current node.
If it’s greater than max width of previous nodes then we have to resize previous nodes and remember it as the new max width.
If a previous node was bigger then we have to resize this node to max width.

Feedback about page:

Optional: your email if you want me to get back to you:

Need fast, offline access to 190+ programmer API docs? Try my app Documentalist for Windows