The struggle of media queries: How can you reset an element to its original display style when it's set to none?

If faced with the following scenario, how would you handle it?

Imagine this: You need to hide a visible element when a specific media query is met:

.myElement {
   display: block;
}

and the media query to hide it:

@media (min-width: 1000px) {
.myElement {
   display: none;
}}

Now, if you want to show a hidden element when a media query is met.

You start by setting its display to none:

.myElement {
   display: none;
}

Then, after using a particular media query for some time and you decide to show it again, so you use:

@media (min-width: 1000px) {
.myElement {
   display: block;
}}

However, now many myElements are using flex layout while others are using block layout, causing the media query to malfunction.

Is there a way to create a media query where it can make the element visible regardless of its display type?

@media (min-width: 1000px) {
.myElement {
   display: initial;
}}

In case the display property is not set on the element class, how does it work? You might specify that the element is currently using Flex but should initially be hidden and then restore a previously defined value:

.myElement {
   display: flex;
   display: none;
}

Does this concept make sense?

Answer №1

In the case where .myElement can exhibit behaviors of either a block or flex element, it is likely that these properties are inherited from other classes. To address this, I have introduced two additional classes: .block and .flex for demonstration purposes.

Furthermore, a new class called .hide has been created to facilitate toggling the display: none property on and off.

Using JavaScript, we can remove the .hide class from the element when it meets certain media query criteria, thereby restoring its original state as a flex or block element.

It's worth noting that there isn't a direct way to remove a class based solely on the media query without leveraging JavaScript functionality.

To fully experience this demo, please view it in fullscreen mode:

let mql = window.matchMedia("(min-width: 1000px)");
let elems = document.querySelectorAll('.myElement')
mql.addEventListener("change", (e) => {
if (e.matches) {
    /* the viewport is 1000 pixels wide or more */
    console.log("This is a wide screen — more than 1000px wide.");
    elems.forEach((elem) => {
        elem.classList.remove("hide");
    });
} else {
    /* the viewport is less than than 1000 pixels wide */
    console.log("This is a narrow screen — less than 1000px wide.");
    elems.forEach((elem) => {
    elem.classList.add("hide");
    });
}
});
* {
font-family: sans-serif;
}

.hide {
display: none !important;
}

.myElement {
padding: 5px 10px;
color: white;
}

.block {
display: block;
background-color: #4c40f7;
}

.flex {
display: flex;
background-color: #f74040;
}
<div class="myElement block hide">
    <div class="block">This is block 1</div>
    <div class="block">This is block 2</div>
</div>
<div class="myElement flex hide">
    <div class="flex">This is flex 1</div>
    <div class="flex">This is flex 2</div>
</div>

EDIT:

In the comments section, @Vladislav proposed an alternative suggestion. If the display: block or display: flex styles applied to .myElement stem from other classes, it may be more efficient to directly modify those classes within the relevant media query. This streamlined approach assumes prior knowledge of which class corresponds to each display property. In cases where classes are dynamically altered, the initial JS method remains preferable.

If you're confident in your understanding of which classes dictate display properties, you can bypass JavaScript entirely by implementing the following CSS solution:

* {
font-family: sans-serif;
}

.myElement {
padding: 5px 10px;
color: white;
}

.block {
display: block;
background-color: #4c40f7;
}

.flex {
display: flex;
background-color: #f74040;
}

@media (max-width: 1000px) { 
.block, .flex {
display: none;
}
}
<div class="myElement block hide">
    <div class="block">This is block 1</div>
    <div class="block">This is block 2</div>
</div>
<div class="myElement flex hide">
    <div class="flex">This is flex 1</div>
    <div class="flex">This is flex 2</div>
</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

Adjust the white background to match the gray background seamlessly

I'm in the process of developing a forum and encountering some challenges with CSS. My goal is to extend the white area all the way to the right edge of the gray background, leaving a gap of around 5px/10px. I've experimented with different CSS ...

Developing interactive checkboxes for individual rows through React.js

Within a form, I have rows containing two inputs each. Upon clicking "add", a new row is created. For the second row onwards, by clicking "add" a checkbox labeled 1 should be added to indicate dependency on the previous row. In addition, for the third row, ...

Issues with retrieving the subsequent anchor element using Jquery Slider

(Apologies for the lengthy post. I like to provide detailed explanations.) Just starting out with Jquery, trying my hand at creating a custom image slider from scratch. Got the slider working with fade effects using this code: Javascript: $(document).re ...

Changing HTML tags programmatically in Angular while inheriting a template

In my project, I have a Component called DataGrid that represents a table with expandable rows. Each row can be expanded to show a child DataGrid table, which is similar to the parent DataGrid component. To simplify this setup, I created a base class DataG ...

What are some strategies for efficiently displaying a large amount of data on a screen using Javascript and HTML without sacrificing performance?

Imagine having a hefty 520 page book with over 6,200 lines of text ranging from 5 to 300 characters each. The challenge lies in efficiently displaying this content on the screen for users to read without causing lag or performance issues. Attempting to re ...

Ways to showcase information from an angular service

I'm struggling with displaying data from a service in my HTML view using AngularJS. My goal is to show a list of submitted forms called Occurrences in the view. When clicking on a list item, I want to be able to view all the data fields submitted thro ...

Creating a Stylish Navigation Bar with Bootstrap4 - Organizing Elements for Just the Right Look

I am trying to organize my content within a navbar into 3 different 'columns'. I want a logo on the left, some navigation items in the center, and the last element ("Get The App") on the right, but I am facing some challenges. Below is my code s ...

The implementation of jQuery within an included HTML file may not function properly

I'm looking to implement the use of includes for generic HTML elements in my project. However, I've run into an issue where including an HTML file causes jQuery to stop working. Here is a snippet of my code that illustrates the problem. Specifica ...

positioning newly generated dropped elements within the DOM structure dynamically

Hello everyone, I have a query related to drag and drop functionality. I am currently working on an application that allows users to create websites using only drag and drop features. I am facing a challenge in implementing a feature where users can drop e ...

Add the information from the form to a JSON document

I am trying to add form data to a json file using the code below. However, I keep getting an error response whenever I submit the data via post. Can you help me identify where the issue lies? HTML <form class="ajax form-inline"> <div class="form ...

What is the method for increasing the left margin of the back button on the default header in React Native?

My attempt to increase the space on the back button from the left side of the header in my React Native code has been unsuccessful. headerStyle: { paddingLeft: 60 } https://i.stack.imgur.com/0RFb0.png I also experimented with adding margin ...

Switching between Angular components with a button press

I'm looking to switch from one Angular component to another when a button is clicked. Specifically, I have two components: app and login. Upon clicking a button in `app.component.html`, I want to navigate to `login.component.html`. Here's what I& ...

swap the positions of two distinct texts

I need to dynamically change the positions of two texts based on the text direction (LTR or RTL) using CSS specifically for an email template. Here is the code snippet I am working with: '<span style="font-weight:bold; text-align: center;">US ...

Having trouble uploading an image to firebase storage as I continuously encounter the error message: Unable to access property 'name' of undefined

Hey there, I'm currently facing an issue while trying to upload an image to Firebase storage. Despite following all the instructions on the official Firebase site, I'm stuck trying to resolve this error: Uncaught TypeError: Cannot read property ...

Error: The column 'joinedactivities.searchact id = searchact.id' is not recognized in the 'on clause'

I keep encountering this particular error: Error: Unknown column 'joinedactivities.searchact id = searchact.id' in the 'on clause'. I have meticulously inspected the table names and even attempted to make modifications, but multiple err ...

What is the best way to use PHP to call an ACF variable and substitute a nested HTML element?

Utilizing the repeater field in Wordpress' advanced custom fields, I have made the content on my site dynamic. View an image of the static markup here The following is how I structured the content using plain HTML: <div class="container" ...

What are the best ways to position elements within a div?

In my small information div, I am looking to align the content on the right side. Specifically, 065 31 323 323, <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a5d4c4c1c0cbdfc4e5c2c8c4ccc98bc6cac8">[email protected]</ ...

Steps for implementing a Toggle Navigation Bar in CSS

I'm looking to implement a show/hide navigation menu similar to the one showcased in this inspiration source: Code Snippet (HTML) <div id="menus"> <nav id="nav"> <ul> <li><a href="#">HOME</a></li> <li& ...

Check the radio box corresponding to the adjacent label

As a hobby, I have been exploring ways to automate questionnaires that I used to manually deal with for years. It has always intrigued me how best to streamline this process, and now I am taking the opportunity to indulge in my passion and enhance my JavaS ...

Creating a personalized navbar design using Bootstrap

I'm attempting to build a navbar using bootstrap 4: However, I am uncertain of how to achieve this :/, can anyone offer any advice?! I am specifically interested in the lines on the left and right of the navbar, as well as the image centered in the m ...