1 Set up nav bar block.
Add your links and ensure it has a parent container (like a Group Block or Header Block) so you can apply styles to it.
2 Custom CSS
You can use the Additional CSS
section in the WordPress Customizer or enqueue a custom CSS file. Here’s the CSS:
/* Default large navbar */
.shrinkable-navbar {
position: fixed;
top: 0;
width: 100%;
height: 100px; /* Initial height */
background-color: #333;
color: white;
display: flex;
align-items: center;
justify-content: center;
transition: height 0.3s ease;
z-index: 1000;
}
/* Shrinked navbar */
.shrinkable-navbar.shrink {
height: 50px; /* Shrinked height */
}
.shrinkable-navbar a {
text-decoration: none;
color: white;
margin: 0 15px;
font-size: 18px;
transition: font-size 0.3s ease;
}
.shrinkable-navbar.shrink a {
font-size: 16px; /* Optionally shrink link size too */
}
3 The JS
You need to enqueue a small JavaScript file in your theme or use a plugin like Code Snippets to inject this code.
Here’s the JavaScript:
document.addEventListener("DOMContentLoaded", function () {
const navbar = document.querySelector(".shrinkable-navbar");
window.addEventListener("scroll", function () {
if (window.scrollY > 50) {
navbar.classList.add("shrink");
} else {
navbar.classList.remove("shrink");
}
});
});
4 Assign shrinkable-nav bar class
In the Block Editor:
- Select the parent container block for your menu (Group or Header block).
- In the Block Settings, under Advanced, add
shrinkable-navbar
as an additional CSS class.
5 Enque js
If you’re using a child theme, you can enqueue the JavaScript in your theme’s functions.php
file:
Create the shrink-navbar.js
file in the /js/
folder of your theme and add your JavaScript there.
function enqueue_shrink_nav_script() {
wp_enqueue_script(
'shrink-navbar',
get_template_directory_uri() . '/js/shrink-navbar.js', // Update the path
array(),
null,
true
);
}
add_action('wp_enqueue_scripts', 'enqueue_shrink_nav_script');
6 In line JS
Messy but maybe works
<script>
document.addEventListener("DOMContentLoaded", function () {
const navbar = document.querySelector(".shrinkable-navbar");
window.addEventListener("scroll", function () {
if (window.scrollY > 50) {
navbar.classList.add("shrink");
} else {
navbar.classList.remove("shrink");
}
});
});
</script>
Adding <script>
tags in a Custom HTML block might not work if WordPress blocks them for security reasons. If this happens, try the other methods above.
Inline JavaScript in content blocks is generally discouraged because it can make maintaining your code more difficult in the long run.
Leave a Reply