Fluctuating behavior when utilizing CSS pseudo-selector :checked to alter the position of a div

I'm currently in the process of shifting towards using pure CSS for interface animations and interactivity. Specifically, I am developing a website where I aim to implement a full-screen menu drawer that drops down when the user clicks on the menu icon.

To achieve this, I have positioned a hidden checkbox within a grid at the top of the screen with a z-index of 2. The menu itself is set to be 100vw and 100vh, initially positioned at -100vh from the top. When the checkbox is checked, I intend to change the position of the menu to be at the top (0px).

However, despite the checkbox appearing functional, checking it does not seem to affect the position of the menu as expected.

Here is an example of the HTML code:

<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://kit.fontawesome.com/793b1590a4.js"></script>
<link rel="stylesheet" href="css.css" />
</head>
<body>
  <div id="top">
    <input type="checkbox" id="mt" />
    <label for="mt" id="mb"><i class="fa fa-bars fa-2x"></i></label>
    <div id="ttl"> Website </div>
    <div id="krt"><i class="fas fa-shopping-cart fa-2x"></i> </div>
  </div>
  <div id="menu">
    <ul id="ul">
      <li>Item 1</li>
      <li>Item 2</li>
      <li>Item 3</li>
    </ul>
  </div> 
</body>

And the corresponding CSS code:

html, body {
  margin: 0;
  padding: 0;
}

#top {
  display: grid;
  position: fixed;
  z-index: 2;
  height: 8vh;
  padding: 1vh 3vw 0 3vw;
  background: #fff;
  grid-template-columns: 10vw 74vw 10vw;
  justify-items: center;
  align-items: center;
}

#mt {
  display: none;
}

#mb {
  grid-column: 1;
}
...
Lines truncated for brevity...
...
} 

While troubleshooting this issue, I created a simplified version which behaves as intended. However, I am struggling to pinpoint the exact reason why the functionality breaks down in my initial implementation. Here's an example of the simplified version that works smoothly:

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://kit.fontawesome.com/793b1590a4.js"></script>
<link rel="stylesheet" href="css.css" />
</head>
<body>
  <input type="checkbox" id="menu-button" />
  <label for="menu-button" class="menu-icon"><i class="fa fa-bars fa-2x"></i></label>
  <div id="menu">
    <ul id="ul">
      <li>Item 1</li>
      <li>Item 2</li>
      <li>Item 3</li>
    </ul>
  </div>
  <div id="container">
    <div id="title">
      Website
    </div>
  </div>
</body>

And its corresponding CSS:

html, body {
  margin: 0;
  padding: 0;
}
...
Lines truncated for brevity...
...
} 

If anyone can provide insights into why toggling the checkbox fails to change the position of the menu in the first scenario but works fine in the second, I would greatly appreciate it!

Answer №1

Unfortunately, the initial example is ineffective due to the utilization of a general sibling combinator (~) in the CSS code for selecting the menu to alter its positioning.

#mt:checked~#menu {}

The general sibling combinator (~) in CSS functions by separating two selectors and only matching the second element if it directly follows the first element, both being children of the same parent element.

Learn more about the general sibling combinator here!


In contrast, the second example shows success as #menu indeed comes after #menu-button within the same parental hierarchy. Here, #menu pertains to the side menu, whereas #menu-button corresponds to the checkbox.

#menu-button:checked~#menu {
  left: 0px;
}

The issues with the first example are manifold. In this instance, #menu symbolizes the side menu, while #mt stands for the checkbox. Regrettably, these elements do not share a common parent in the HTML structure. As observed, the #menu entity happens to be a sibling of the #mt checkbox's parent instead.

#mt:checked~#menu {
  top: 0px;
} 

Subsequently, I suggest resorting to Javascript for achieving this functionality. Relying solely on CSS constrains you into adhering strictly to particular HTML configurations that align with the CSS selectors.

Moreover, this method lacks provisions for implementing accessibility enhancements. While these examples serve educational purposes, they can pose challenges for individuals utilizing screen readers, those with visual impairments, or those with mobility limitations. It's worth noting that approximately 15% of the global population contends with some form of disability, underscoring the significance of ensuring inclusivity in web design endeavors.

For more insights on disabilities, refer to this resource!

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

I'm receiving the error message "Fatal error: Call to a member function query() on a non-object," what could be causing this issue?

Need help with fixing an error on my private server realmeye. The error message I'm receiving is: Fatal error: Call to a member function query() on a non-object in /home/noxus/public_html/realmeye/index.php on line 112 =========================== ...

I'm having trouble customizing the appearance of a checkbox. I want it to change color when clicked, but I can't seem to get it to stay in

In order to achieve the desired effect where the white part should appear on the tick, initially the entire thing should be black and then turn white upon clicking. I am currently working on this in Storybook and would appreciate help with positioning. htt ...

Trigger sound when it is fully loaded using HTML5 and JavaScript

Looking for a way to make your HTML5 audio file automatically play as soon as it loads on the page? I've got you covered. Thanks in advance! ...

Is it possible for an animation to complete even if it is stopped midway?

I am currently working on a media player project where I have implemented a scrolling marquee effect for the song meta information using JavaScript and CSS. The scrolling effect only occurs when the track is playing, and I achieve this by adding/removing ...

Center 3 elements horizontally using Flexbox, ensuring the center element is aligned properly

Is it possible to center 3 elements using flexbox on a page? The middle element should be centered on the page, while the left and right elements can vary in width. Please refer to the image below: https://i.sstatic.net/IVdz8.png I am not certain if this ...

When I use Input.value, it seems to cause a strange lag in my console.log

My goal is to have a text input on the page that triggers #fourChord's text to change as I type characters into the input. The issue I am facing is that console.log registers my input, but the first character is always ignored. For example, if I type ...

How to align content in the center horizontally and vertically using HTML and CSS

I'm having trouble centering my content both vertically and horizontally on the page. Can anyone provide assistance? Thank you. <style type = "text/css"> #loginMenu { border:5px solid green; padding:10px 10px 10px 10px; background-color:#FF9; ...

"Displaying overflow content by scrolling causes the div to be positioned

Within a container div with overflow hidden, I am struggling to display one object outside of the div while still keeping it visible. Can anyone offer guidance on how to achieve this? I'm unsure about the proper approach. I would appreciate any sugge ...

What is the best way to apply a unique style to the currently active tab in a sidenav based on

I am in the process of creating a side navigation bar where I want to incorporate a left border on the active tab. How can I achieve this by utilizing state and passing a boolean value as a prop to the Child SideNavItem class, then updating it with each ta ...

Dealing with numerous ajax requests simultaneously with the help of $q.all

I am attempting to make multiple AJAX calls on my page using the $q method. After receiving all the responses, I am trying to store them in a single array. However, it seems like this process is not functioning as expected. Here is my controller: I have ...

Populate HTML dropdown menu with data from an external JSON file

I'm attempting to populate a HTML Dropdown menu with information from an external JSON file, which consists of the following { "Destinations": [ { "destinationName": "London", "destinationID": "lon" }, { "dest ...

Tips for customizing the appearance of a collapsed Bootstrap 4 Accordion heading

Is there a way to customize the styling of a Bootstrap 4 accordion so that the header changes color when opened and closed? Which classes should be targeted in order to achieve this effect, such as making the heading red when the accordion is open and gray ...

"Encountered a 404 Error while attempting an Ajax

I am relatively new to web development and I am currently working on making a post method function properly. Below is the ajax call that I have implemented: $.ajax({ type: "POST", url: '/Controllers/AddPropertyData', ...

Tips for concealing a div outside the viewport while ensuring the bottom 50px always remains visible

I am trying to achieve an effect where I can move a div off the screen (top up) while keeping the bottom edge visible, specifically 50px. Currently, my approach involves hiding 90% of the div using jQuery and CSS3 with jquery.transit for cross-browser comp ...

CSS/JavaScript - why is my button and link not responding to hover or click events, even when I set the z-index to

Experiencing a peculiar issue that seems unrelated to z index - I originally had this as an a href and now changed it to a button, but both still have the same problem of mouse hover and mouse click NOT registering at all. This is the HTML snippet: <? ...

The HTML generated by Angular does not display as anticipated

When converting the angular-generated HTML to a PDF using jspdf, it does not take into consideration angular classes like ng-hide. This means that elements styled with the ng-hide class will still appear in the generated PDF. To see an example, visit the ...

Controlling File Upload Edits: A Guide to Effective Management

I am facing an issue on my product page related to adding and updating products in the database. The problem lies with images not displaying correctly. During the product insertion process, everything works fine. In my aspx page, I have the following code ...

What is the best way to make a JavaScript cookie remember the state of a DIV?

Seeking assistance with a test site here that is currently in development. I am attempting to make the notification at the top remain hidden once the close button is clicked. Below is my current script: <style type="text/css"> <!-- .hide { displ ...

Updating the background color and adjusting the main content background on a WordPress site

After spending nearly an hour searching for a solution to my problem with no luck, I've come to the conclusion that most YouTube videos are not helpful at all. My website is built on WordPress and I am attempting to change the background color and mai ...

JavaScript loaded only on first visit or after the page is refreshed

For my cross-platform app using Cordova and jQuery Mobile 1.4.5, I have a basic html page that needs to load a javascript file. <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Security-Policy" content="default-src ...