WordPress admin bar height and CSS custom properties
Published: – Leave a comment
If you want to properly take the admin bar into account in your theme, you always need to adjust it if you have a fixed/absolute positioned header. With CSS custom properties, it becomes much less of a pain.
Given that you have a menu bar inside your page-header
element, which is positioned fixed on top:
.page-header {
inset-block-start: 0;
inset-inline: 0;
position: fixed;
z-index: 10;
}
Code language: CSS (css)
This shows the page header always on top. However, if the admin bar is enabled for logged in users, the page header is hidden (or at least a part of it) behind the admin bar, since the latter is positioned absolute on top.
With CSS custom properties, you can define the height of the admin bar in different conditions and then just use a single line in your page header code to automatically adjust it every time.
By default, for guests, there is no admin bar, so set it’s height to 0px
in you custom property:
body {
--my--size--admin-bar--height: 0;
}
Code language: CSS (css)
If the admin bar is visible, it may have two different sizes. On desktop, its height is 32px
while on mobile (< 783px
) its height is 46px
. Since I use the same media query here, which has a separate query for the mobile version, the override for the custom property looks like this:
.admin-bar {
--my--size--admin-bar--height: 32px;
}
@media screen and (max-width: 782px) {
.admin-bar {
--my--size--admin-bar--height: 46px;
}
}
Code language: CSS (css)
The class admin-bar
is always available to the body
element if the admin bar is visible.
In the page header CSS, you can then just use this code:
.page-header {
inset-block-start: var(--my--size--admin-bar--height);
}
Code language: CSS (css)
The custom properties’s value always automatically adjusts depending on whether the admin bar is visible or not and depending on the viewport’s size.