Roma’s Unpolished Posts

Calculation Indentation

Published on:
Categories:
CSS Formatting, CSS 37
Current drink:
Yunnan tea

For some time, I struggled with some of the more complicated calculations in CSS. Not with their contents, but with how I would like to see them formatted.

Let’s say we have some CSS like this (taken from the styles of this blog):

body {
	--content-padding: calc(var(--MIN-CONTENT-PADDING) + clamp(0px, 100vw - var(--CONTENT-WIDTH), 2rem));
}

ul, ol {
	padding-inline-start: calc(2 * var(--MIN-CONTENT-PADDING) - var(--content-padding));
}

It is not the most complex CSS, but it is already difficult to read and maintain.

How Prettier Handles It

Let’s imagine we’d use Prettier for this. As I’m going to display it here in my blog, by default it has around 54 symbols available with the tab-size: 2. Putting these settings in Prettier gives us this:

body {
	--content-padding: calc(
		var(--MIN-CONTENT-PADDING) +
			clamp(
				0px,
				100vw - var(--CONTENT-WIDTH),
				2rem
			)
	);
}

ul,
ol {
	padding-inline-start: calc(
		2 * var(--MIN-CONTENT-PADDING) -
			var(--content-padding)
	);
}

Well, I guess, better, but I don’t really like Prettier’s way of bumping the indentation when wrapping a line of calculations.

And I never liked how Prettier formatted many other things in CSS, so I would probably never want to use it for my styles.

How I Ended Up Writing It

And here is what, after many thoughts, I ended up doing:

body {
	--content-padding: calc(
		var(--MIN-CONTENT-PADDING)
		+
		clamp(
			0px,
			100vw - var(--CONTENT-WIDTH),
			2rem
		)
	);
}

ul, ol {
	padding-inline-start: calc(
		2 * var(--MIN-CONTENT-PADDING)
		-
		var(--content-padding)
	);
}

A few things to note there.

Another Example

Here is another (again, rather simple) example, this time from my Using the Connections experiment of my Future CSS: Anchor Positioning article.

How I did write it in the article:

.tree-item-label::before {
  top: calc(anchor(var(--to) top) + 0.5 * var(--lh));
}
.tree-item-label::after {
  bottom: calc(anchor(var(--to) top) - 0.5 * var(--lh));
}

How Prettier formats it:

.tree-item-label::before {
	top: calc(
		anchor(var(--to) top) + 0.5 * var(--lh)
	);
}
.tree-item-label::after {
	bottom: calc(
		anchor(var(--to) top) - 0.5 * var(--lh)
	);
}

Verbose, but does not really help.

How I would now prefer to write it:

.tree-item-label::before {
	top: calc(
		anchor(var(--to) top)
		+
		0.5 * var(--lh)
	);
}
.tree-item-label::after {
	bottom: calc(
		anchor(var(--to) top)
		-
		0.5 * var(--lh)
	);
}

Now it is much easier to spot the main difference of the + vs the -, as well as distinguish between the calculation arguments.

It’s All Subjective

That’s just the way I, at the present day, decided to write my CSS. Maybe it won’t fit you! Perhaps I would change it later! Or there would be things I reconsider and add to this method! We will see.

Please share your thoughts about this on Mastodon!