I have a simple navbar, mostly copypasta'd from Bootstrap's navbar tutorial. Basically, I put padding on a form using the Bootstrap class "pe-5" (I only used pe-5 to demonstrate this better, I will probably reduce it if I can fix this), so it's aligned to the right of the navbar with some space from the edge of the screen, and a collapsible button that appears when the form is flex wrapped (please excuse my vocabulary as I am new to both webdev and bootstrap (and flexbox)). However, when the button is collapsed (so when I shrink the window until the button appears, and then click the collapse button), the padding is still there on the form input and search button and it looks weird and off.
Is there a way to change the CSS for collapsed items? I've tried many things, including changing the CSS for when the collapse is shown:
#navbarCollapse.navbar-collapse.collapse.show #top-search-form {
padding-left: 0rem;
padding-right: 0rem;
}
However nothing seemed to change. And I'm fairly certain I have the CSS path correct as changing the margins seems have an effect but changes it while the animation starts so it looks like it "jumps" as it is collapsing. Regardless, changing the padding does nothing. I've also tried a few other CSS methods that I can't remember off the top of my head.
I also tried using Javascript but it became extremely messy and I feel like there is a much simpler solution. What I tried was adding event listeners for when the collapsible button was shown and hidden and would add/remove the pe-5 class using classList.remove(), but I ran into a problem that when resizing the window, if the button is collapsed but hidden, it is still considered "collapsed" and the bootstrap padding class would still be removed. Then I tried adding an event listener to window resize and it became very messy and I could not get it to work as intended as finding if an element is overflown through flex is a lot harder than I thought, and I figured this would end up slowing my page down significantly.
Here is an example of the issue I am having:
https://jsfiddle.net/jbu812os/
Just shrink the screen until the collapse hamburger button appears and click it and it should show that the input search box and search button are not taking up the full collapse width.
Any help would be GREATLY appreciated, thank you!
CodePudding user response:
Try adding these two jQuery event handlers:
$('#navbarCollapse').on('show.bs.collapse', function() {
$('#top-search-form').removeClass('pe-5')
})
$('#navbarCollapse').on('hidden.bs.collapse', function() {
$('#top-search-form').addClass('pe-5')
})
I am using the built in Bootstrap events and they seem to work.