CSS custom property to offset the WordPress admin toolbar height
Some niceties pop up in WordPress versions that are easy to miss.
Here's one that I almost did: "a CSS custom property to offset the admin toolbar height" introduced in version 5.9.
Let's take this CSS code from a default theme:
.screen-height {
min-height: 100vh;
}
.admin-bar .screen-height {
min-height: calc(100vh - 32px);
}
@media (max-width: 782px) {
.admin-bar .screen-height {
min-height: calc(100vh - 46px);
}
}
All this work is required because we might or might not have the admin bar. And if we do, the height of the admin bar changes based on the screen size.
Something similar is found in many themes; it's almost boilerplate code.
With the introduction of --wp-admin--admin-bar--height
, if we would refactor this piece of code, we could do the following:
.screen-height {
min-height: calc(100vh - var(--wp-admin--admin-bar--height, 0px));
}
It's much more convenient because we no longer have to care about the logic behind all the cases; we only have to retrieve the exposed calculated height.