conceal Bootstrap dropdown using specific media query conditions

I am facing an issue with a bootstrap dropdown that remains open even after the screen is resized to hide the dropdown button. I have searched for a solution, but none of the answers I found have helped me so far.

Is there a way to close the dropdown or remove the "show" class for the menu based on a media query? I want the dropdown menu to close smoothly like on some other websites.

What CSS code can I use to achieve this? Currently, the dropdown stays open until it loses focus, but I want it to close automatically. Below is a snippet of the CSS I am using:

.sm-screen-dropdown-menu {
  top: 48px !important;
  box-shadow: rgba(0, 0, 0, 0.16) 0px 10px 36px 0px, rgba(0, 0, 0, 0.06) 0px 0px 0px 1px;
  border: none;
  border-radius: 0px;
  padding: 0;
  min-width: 200px;
}

@media (max-width: 600px) {
  .hide-sidebar {
    display: none !important;
  }
  .sm-screen-dropdown {
    display: flex;
    font-size: 20px;
    margin-right: 15px;
    margin-left: 10px;
    text-decoration: none;
  }
  .sm-screen-dropdown:hover {
    cursor: pointer;
  }
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6b0904041f181f190a1b2b5e4559455b">[email protected]</a>/dist/css/bootstrap.min.css" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.2/css/all.min.css" integrity="sha512-1sCRPdkRXhBV2PBLUdRb4tMg1w2YPf37qatUFeS7zlBy7jJI8Lf4VHwWfZZfpXtYSLy85pkm9GaYVYMfw5BC1A==" crossorigin="anonymous" referrerpolicy="no-referrer" />

<div class="dropdown center">
  <div class="sm-screen-dropdown" dropdown-toggle type="button" data-bs-toggle="dropdown" aria-expanded="false">
    <i class="fa-solid fa-bars menu-icon"></i>
  </div>
  
  <ul class="dropdown-menu sm-screen-dropdown-menu" aria-labelledby="dropdownMenuLink">
    <li>
      <a class="dropdown-item" href="/">Home</a>
    </li>
    <div class="dropdown-divider no-margin"></div>
    <div class="ms-2">
      <li>
        <a class="dropdown-item" href="{% url 'home' %}">Groups</a>
      </li>
      <li>
        <a class="dropdown-item" href="{% url 'taglist' %}">Tags</a>
      </li>
    </div>
  </ul>
</div>

<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="30525f5f44434442514070051e021e00">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa" crossorigin="anonymous"></script>

Answer №1

Your code is not being executed within a snippet, which can make it difficult to understand the full context. However, I have quickly put together an example to demonstrate how to show/hide elements based on a media query using JavaScript instead of CSS.

If you run the snippet in full page mode, inspect the elements, and reduce the viewport width, you will notice the circle disappearing when the viewport width is less than 576px.

You can also refer to this Codepen link for further reference.

const smallDevice = window.matchMedia("(min-width: 576px)");
let circle = document.querySelector(".shape.circle");

smallDevice.addListener(handleDeviceChange);

function handleDeviceChange(e) {
  if (e.matches) circle.style.display = 'block';
  else circle.style.display = 'none';
}

// Run the function initially
handleDeviceChange(smallDevice);
body {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  height: 100vh;
}

.shape {
  width: 250px;
  height: 250px;
  border: 1px solid black;
}
.shape + .shape {
  margin-top: 1rem;
}
.shape.box {
  background: blue;
}
.shape.circle {
  border-radius: 50%;
  background: red;
}
<div class="shape box"></div>
<div class="shape circle" style="display: none;"></div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Personalized CSS designs within the <option> element in an expanded <select> menu

Are there alternative methods for customizing an expanded select list using HTML or a jQuery plugin? I am interested in rendering each option in the list with multiple styles, similar to this example where the number is displayed in red: <select size=" ...

What is the best method to style a child input element's placeholder using Tailwind CSS?

I'm currently working on a project and trying to translate a CSS style that targets the ::placeholder pseudo-element into Tailwind CSS. However, I have encountered some challenges during this process as I'm not entirely sure of the correct approa ...

WordPress having trouble rendering the stylesheet code

I am facing an issue with Wordpress where my CSS file is not loading properly. The stylesheet contains a rule to center the header image, but for some reason it's not working. I've also tried adding a margin-left of 100px, but that doesn't s ...

Manipulating Objects with CSS Transform in Global/Local Coordinates

If we take a closer look at our setup: <div id="outside"> <div id="inside">Foo</div> </div> and apply a rotation to the outer element - let's say turning it 45 degrees clockwise: <div id="outside" style="transform: ro ...

Is it advisable for postcss plugins to list postcss as a peer dependency?

I'm trying to incorporate the PostCSS Sass Color Function into my project. Unfortunately, I encountered this error: PostCSS plugin error: Your current version of PostCSS is 6.0.22, while postcss-sass-color-functions requires 5.2.18. This discrepa ...

How can a full-screen background image be created in Next.js?

To achieve a full height display in both the html and body tags, how can we do this within a next.js component? Check out [1]: https://i.stack.imgur.com/K1r9l.png [2] Visit: https://www.w3schools.com/howto/howto_css_full_page.asp "mainImage.jsx" import ...

What is the best way to position two out of the three link tags to the right side?

This is the code snippet I am currently working with: <table> <tr> <td>&nbsp;</td> <td> <a id="btnAutoSuggest">Suggest Title</a> <a id="btnOK">OK</a> <a id ...

Changing the background color of a React styled-component when hovered over

Is there a way to create a custom div with an interactive hover effect that changes the background color? I am using styled components and passing in the color as props, but for some reason, the hover effect is not functioning correctly. const ColorBlock = ...

If a certain criteria is met, the user will be redirected to a specific page. If the criteria is not met, they will be redirected

How can I redirect the page to success.html if a certain condition is met using class-based views, and redirect to faild.html if it's not met? class LogView(FormView): form_class = LogForm template_name = 'log.html' success_url= ...

Enhance your Django admin experience: create a custom app_index with personalized context

When working with Django admin, it is possible to set up custom templates for each app. In my current scenario, I am customizing the app_index.html template for a specific application. My goal is to include some graphs and additional content on this page. ...

Increase the spacing between rows and columns in Bootstrap

Is there a way to create gaps between rows and columns in bootstrap without disrupting the layout? I am trying to have three columns on each row by using col-4, but when I try to add margin or padding, it messes up the design. My goal is to achieve a layo ...

Center sidenav material 2 in alignment

Using Angular Material 2 presents a challenge for me: While I can align the text in the sidenav to center, I am struggling to align the button correctly. https://i.sstatic.net/vjHw4.png <md-sidenav-layout fullscreen> <md-sidenav #start mode=" ...

Interactive feature in Three.js causes page to scroll downwards upon object selection

Exploring Three.js for the first time, I'm looking to integrate it into the landing page of my website. However, I've encountered an issue where clicking on the scene area with my object causes the page to shift downward. I've tried adding o ...

Update the query string to accommodate several values

Having an issue with my query string. Whenever multiple values are selected, my Django search function malfunctions. The URL displays ?Query=value1&Query=Value2, but only the last value is actually searched. I need both values to be searched using an A ...

Tips for updating border color when focused with styled-components

How can I change the border color of an input on focus using styled-components and React? Here is the code snippet I am currently using: import React from "react"; import PropTypes from "prop-types"; import styled from "styled-components"; const String ...

Is there a way to selectively display a portion of my CSS class based on certain conditions?

Is there a way to conditionally render all of the css inside the following hover psuedoclass based on a variable (data) being not null? Within my React Component that utilizes Material UI makeStyles, I have the following styles: const useStyles = makeStyle ...

What could be causing my form to not be centered on the screen?

Currently working on creating a form for adding books to a fictional library website. The form tag is enclosed within a div, but despite the CSS styling applied, it remains fixed to the left side of the screen and I'm struggling to understand why. .fo ...

Struggling to get the max-width property to function properly with a Bootstrap multi-level dropdown menu

I have a multi-level Bootstrap dropdown menu that I am customizing based on the design featured in this bootsnipp. However, I am encountering an issue where some of my menu items are too lengthy, so I need to restrict their width to a maximum of 400px. Ad ...

The absence of the definition of DJANGO_SETTINGS_MODULE is causing an issue during the creation

I've been looking at this tutorial to help me create documentation for my Django project. In the conf.py file located in my documentation directory, I included sys.path.append(os.path.join(os.path.dirname(__name__), '..')). However, whenev ...

I need the links to open up the content area on the website in HTML

Is it possible to have a fixed header that does not disappear when clicking links from the navigation bar? I tried dividing the page into tables to achieve this. Now, I want to open the links in the navigation bar in the right column (the main content col ...