Utilizing CSS for displaying and hiding content based on its unique identifier

Is it possible to show/hide a div using only CSS based on its ID?

Showcasing this functionality in jQuery or vanilla JavaScript is straightforward, but can the same effect be achieved with pure CSS?

The checkbox hack requires a specific structure to function properly.

Furthermore, I would prefer if the div was hidden only until the next h1 element appears, if applicable.

label:after {
  content: " [show]";
  cursor: pointer;
  float: right;
}

p {
  display: none;
}

input[type=checkbox] {
  display: none; 
}

input[type=checkbox]:checked + div {
  display: block;
}

input[type=checkbox]:checked ~ label:after {
  content: " [hide]"
}
<h1>
  Vampires and Vegetarians 
  <label for="Vampires_and_Vegetarians"></label>
</h1>
<input type="checkbox" id="Vampires_and_Vegetarians">
<div id="Vampires_and_Vegetarians">
  <p>Content for Vampires and Vegetarians</p>
</div>

Answer №1

To ensure that your checkbox can effectively control elements, it needs to be positioned before them in the dom. I have rearranged it to the top for you.

I made some adjustments to your CSS code as well. Initially, you were hiding the p element and then trying to display the div, but now we are hiding the div and then showing it.

Additionally, I switched your use of + to ~ since the div was not a direct sibling.

input[type=checkbox] {
  display: none;
}

input[type=checkbox]:checked~h1 label:after {
  content: " [hide]"
}

label:after {
  content: " [show]";
  cursor: pointer;
  float: right;
}

input[type=checkbox]~div {
  display: none;
}

input[type=checkbox]:checked~div {
  display: block;
}
<section>
  <input type="checkbox" id="Vampires_and_Vegetarians">
  <h1>
    Vampires and Vegetarians
    <label for="Vampires_and_Vegetarians"></label>
  </h1>
  <div id="Vampires_and_Vegetarians">
    <p>Content for Vampires and Vegetarians</p>
  </div>
</section>
<section>
  <input type="checkbox" id="Zombies_and_Zucchini">
  <h1>
    Zombies and Zucchini
    <label for="Zombies_and_Zucchini"></label>
  </h1>
  <div id="Zombies_and_Zucchini">
    <p>Content for Zombies and Zucchini</p>
  </div>
</section>

I trust this information proves to be beneficial for you 🙂
Don't hesitate to seek further clarification if needed.

Answer №2

To ensure proper targeting of sibling elements, it is necessary to adjust the hierarchy of the elements as shown below. Avoid using the same id multiple times within a page.

label:after {
  content: " [show]";
  cursor: pointer;
  float: right;
}

.content {
  display: none;
}

input[type=checkbox] {
  display: none;
}

input[type=checkbox]:checked~.content {
  display: block;
}

input[type=checkbox]:checked~h1 label:after {
  content: " [hide]"
}
<div>
  <input type="checkbox" id="1">
  <h1>
    1
    <label for="1"></label>
  </h1>
  <div class="content">
    <p>Content for 1</p>
  </div>
</div>
<div>
  <input type="checkbox" id="2">
  <h1>
    2
    <label for="2"></label>
  </h1>
  <div class="content">
    <p>Content for 2</p>
  </div>
</div>

Answer №3

It is important to note that an ID cannot be repeated within the same page. For more information on the difference between IDs and classes, you can check out this link: https://css-tricks.com/the-difference-between-id-and-class/

Your code seems correct, but there was a slight issue with the structure. Please refer to the snippet below for the corrected version.

label:after {
  content: " [show]";
  cursor: pointer;
  float: right;
}

div {
  display: none;
}

input[type=checkbox] {
  display: none; 
}

input[type=checkbox]:checked ~ label ~ div {
  display: block;
}

input[type=checkbox]:checked ~ label:after {
  content: " [hide]"
}
<input type="checkbox" id="Vampires_and_Vegetarians">
<label for="Vampires_and_Vegetarians">Vampires and Vegetarians</label>
<div><p>Content for Vampires and Vegetarians</p></div>

I hope this clarifies things for you :)

AFTER READING A COMMENT:

If you have multiple divs and want to show/hide their content using checkboxes, simply give each div a unique ID. That's all you need to do :)

Refer to the example below for a clear demonstration.

label:after {
  content: " [show]";
  cursor: pointer;
  float: right;
}

section {
  display:block;
  margin-top:20px;
}

div {
  display: none;
}

input[type=checkbox] {
  display: none; 
}

input[type=checkbox]:checked ~ label ~ div {
  display: block;
}

input[type=checkbox]:checked ~ label:after {
  content: " [hide]"
}
<section>
<input type="checkbox" id="Vampires_and_Vegetarians1">
<label for="Vampires_and_Vegetarians1">Vampires and Vegetarians 1</label>
<div><p>Content for Vampires and Vegetarians 1</p></div>
</section>

<section>
<input type="checkbox" id="Vampires_and_Vegetarians2">
<label for="Vampires_and_Vegetarians2">Vampires and Vegetarians 2</label>
<div><p>This is the second paragraph</p></div>
</section>

<section>
<input type="checkbox" id="Vampires_and_Vegetarians3">
<label for="Vampires_and_Vegetarians3">Vampires and Vegetarians 3</label>
<div><p>This is the third paragraph</p></div>
</section>

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 puzzled as to why the hidden input field consistently returns the same value every time

As a beginner in php, I am facing an issue where I cannot trace the correct value of the hidden input which represents the ID of the image in the products table. Every time I try to delete an image, it always returns the ID of the last image in the product ...

Understanding the Hierarchy of CSS and Bootstrap Styles

I have been using a custom CSS file along with bootstrap. Initially, I had my custom CSS written before the Bootstrap CSS. However, I recently discovered that it's recommended to include Bootstrap CSS first before any custom CSS. As a result, I'm ...

How can I show/hide a div based on checkbox click on my website? It works in jsFiddle, but not on my actual site. Any suggestions?

Is there a way to show or hide a div based on a checkbox click? I've got it working in jsFiddle, but for some reason, it's not functioning properly on my website. Any thoughts on how to fix this? My goal is to offer multiple payment methods (cre ...

When using jQuery to enable contenthover on divs, they will now start a new line instead of

I've been working on achieving a layout similar to this, with the contenthover script in action: Mockup Draft Of Desired Look However, the result I'm getting is different from what I expected, it can be seen here. The images are not aligning co ...

Utilizing Javascript to implement a tooltip feature for dynamically inserted text

I recently incorporated a brief jQuery tooltip plugin into my site. It consists of approximately ten lines of code and works smoothly, as demonstrated in this demo. However, I encountered an issue when attempting to add new text that should also trigger t ...

"Placing drop-down animations in just the right spot

I'm currently working on adjusting the dropdown behavior for thumbnails when hovering over them. I want the drop-down to appear beneath the 'Caption Title' instead of above the image, but so far my CSS adjustments haven't been successfu ...

Center Text Field to Linear Progress in React

I'm struggling to position a TextField/Autocomplete with a loader/linear progress at the bottom without it pushing the TextField/Autocomplete upwards. Can anyone suggest a proper solution for this issue? For reference, you can check out the Codesandb ...

Refresh iOS / iPad website only upon scrolling, not when utilizing anchor links

Currently, I am in the process of troubleshooting this website: This site is hosted on a LAMP server and is utilizing CMSMS 2.1x, if that detail makes any difference. (By the way, the smarty components are causing some performance issues.) While the desk ...

Unique and responsive grid styling with CSS

Is it possible to create a responsive grid like the one shown in the image below? I attempted to use absolute positioning for all blocks, but I'm having trouble making it responsive... I should note that the styling will be generated dynamically usi ...

The Reason Behind Angular Error when Using CSS Custom Tags

I have the following SCSS code: main{ width: 100%; height: 840px; /*background: red;*/ margin: 10px auto; position: relative; padding: 5px 0; } section{ width: 98%; height: 600px; margin: auto; display: flex; ...

What is the best way to convert this JavaScript iteration function into jQuery?

I recently encountered an issue with my JavaScript function that returns a list of elements with the class ".youtube", loops through them, and calls another function. The JavaScript logic is flawless, but I wanted to convert it into jQuery for better reada ...

One cool CSS trick: altering a div's background color with hover!

I'm working on creating a div that acts as a link to another page. My goal is to have the entire background color of the div change to blue when someone hovers over it. I want to achieve this effect using CSS only, as I am not sure if javascript will ...

Renew The Dining Surface

I am looking for a way to update the table content without refreshing the entire page. I am using HTML, CSS, and JavaScript to display the current data from my sqlite3 database. Any tips on how to achieve this would be appreciated. ...

A guide on how to selectively blur and make the background transparent in jgrowl notifications without affecting the content

After some experimentation, I found that making the jGrowl notification background both transparent and blurry was not possible. When applying blur to the background, the content also became blurry, which is not the desired effect. If you want a transparen ...

The full width of the div exceeds the parent's width, resulting in the box size being ineffective

I'm experiencing an issue where my cover is wider than my element and content. It seems to be covering the gunter, but I've tried using background-clip: content-box; and box-sizing: border-box;, which haven't resolved the problem. I also wan ...

Parent menu fails to trigger the opening of child menu upon clicking

I'm struggling to modify a Wordpress theme to enable the child menus to expand when clicking on the parent menus. Is there a way to edit this code to make that functionality work? // Implement expandable menus var expand_link = $('<a class="m ...

What is the best way to right-align a label in a vertical MUI Slider in ReactJS?

I am currently working with ReactJS/TS and MUI (Material-UI) to develop a vertical slider that requires the label to be positioned on the right side. By default, MUI places the label on the left for vertical sliders. I have reviewed the API documentation e ...

When adjusting the window size with the <ion-split-pane>, both the menu and router outlet disappear

When I have two ion menus and one main content (router outlet) and resize the page or switch to mobile view, the page appears blank as if the content is missing. Here is the code: <ion-app> <ion-split-pane> <ion-menu side="start" me ...

Guide to designing a CSS gradient with a downward arrow linked to a specific container

I'm attempting to add a triangular arrow beneath the v-container, complete with a gradient color scheme. However, I'm struggling to integrate the gradient seamlessly. If I use CSS to create the arrow, the gradient doesn't align correctly. ...

The mouse coordinates do not align with the drawing of a rectangle on the canvas

I am having some issues with drawing a rectangle on mouse drag over the canvas that is overlayed on an HTML5 video JS player. The rectangle is being drawn, but it does not align correctly with the mouse coordinates. I suspect that the canvas, which is ove ...