Displaying or concealing a division depending on a radio button selection (CSS exclusive)

Looking for a solution using only CSS, I could use Javascript/Jquery but trying to avoid it.

In essence, I need one div to be displayed when the first radio button is selected and another div when the second radio button is selected.

I've set up a simplified version of my issue on JSFiddle here, but I can't seem to get it to work in the JS fiddle or my code.


    <label>
<input id="Type1" name="UserType" type="radio" value="Contractor">
            Contractor
</label>

<label>
<input id="Type2" name="UserType" type="radio" value="Managment">
             Managment
</label>

<div class = "hideAtStart" id = "contractorDisplay">
  Show me I'm a contractor.
</div>

<div class = "hideAtStart" id = "ManagerDisplay">
  Show me I'm a managerr.
</div>

CSS

.hideAtStart {
display: none;
}

#Type1:checked ~ #contractorDisplay{
  display : block; 
}

#Type2:checked ~ #ManagerDisplay{
  display : block; 
}

Question

How do I make a div appear when a radio button is clicked?

**Extra Challenge **

Bonus points if you can make the transition fade in/out.

Answer №1

Guidelines for Layout

  1. Begin by setting each radio button before a div (in this case, a fieldset)

  2. For each radio button:

    • Give it a unique #id
    • Assign the same [name]
  3. Create two labels with the attribute [for] and match their values to the #id of a corresponding radio button. This synchronizes the labels with their respective radio buttons.

  4. You can place these labels anywhere on the page as desired.

  5. To simplify things, assign a class that groups similar elements together.


Styling Recommendations

  1. Hide both the radios and the subsequent div after each radio by using display:none

  2. Create the following rule set (taking into account step 5 from the Layout section)

    .radio:checked + .classOfDiv { display:block }
    

    Browsers read CSS rulesets in reverse: When an element with the className .classOfDiv is followed by a sibling element (appearing before or above it in the code) with the className .radio that is also checked, set the display property of .classOfDiv to block.

    The + sign signifies an Adjacent Sibling Combinator, which is crucial for this rule set. Refer to the References section post-Demo for more information.


Demonstration

.rad,
.set {
  display: none;
  opacity: 0;
}

.rad:checked+.set {
  display: block;
  opacity: 1;
}

.btn {
  display: inline-block;
  border: 2px inset grey;
  border-radius: 6px;
  padding: 2px 3px;
  cursor: pointer
}

.btn:hover {
  border-color: tomato;
  color: tomato;
  transition: .75s ease;
}

legend {
  font-size: 1.5em
}
<form id='main'>
  <fieldset>
    <legend>SWITCH</legend>
    <label for='rad0' class='btn'>OPEN SET 0</label>
    <label for='rad1' class='btn'>OPEN SET 1</label>
  </fieldset>

  <input id='rad0' class='rad' name='rad' type='radio'>

  <fieldset class='set'>
    <legend>SET 0</legend>
  </fieldset>

  <input id='rad1' class='rad' name='rad' type='radio'>

  <fieldset class='set'>
    <legend>SET 1</legend>
  </fieldset>
</form>

Resources

Adjacent Sibling Combinator

for Attribute

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

Blurring the edges of a div container

I have successfully faded the top of a div, but I am struggling to achieve the same effect for the bottom. I attempted to reverse the CSS properties used for fading the top, but it does not seem to be working as expected. HTML: <div class="container-c ...

Concealing a Div element without the use of Jquery or JavaScript

I have an Upper and Lower div in my HTML code. I am trying to display the Lower div only if the Upper div is present, otherwise hide it. Is there a way to achieve this using CSS without using Jquery or Javascript? Note: No modifications should be made t ...

Experienced an unexpected setback with the absence of the right-click capability on a Javascript-powered hyperlink, specialized for

I am facing an issue with a hyperlink on my website. This particular hyperlink submits a hidden form using the POST method to redirect users to another site. However, when someone right-clicks on this hyperlink and tries to open it in a new tab, they are o ...

Creating a Hover Effect for DIV Elements Using Pure CSS, No JavaScript Needed

Imagine a straightforward, horizontal navigation on a website: | Home | About | Products | Contact | Impress | ... or something like that... A rectangular element is positioned above the navigation. Now, I want this rectangle to automatically shift hori ...

How can I set a checkbox as mandatory using ng-messages and Ionic framework?

I am currently developing a form for my application using Cordova CLI 8.0, Ionic 1.3.5, and AngularJS 1.5. My goal is to set a checkbox as required within the form. Here's the approach I have taken so far: <ion-checkbox name="entry.exportcode" n ...

How can I retrieve the transformation matrix for a DOM element?

Is there a way to retrieve the transformation matrix of a DOM element similar to how we can do it with canvas context? Does the DOM provide a getTransform() method for this purpose? ...

What is the best way to pass a value to a modal and access it within the modal's component in Angular 8?

How can I trigger the quickViewModal to open and send an ID to be read in the modal component? Seeking assistance from anyone who can help. Below is the HTML code where the modal is being called: <div class="icon swipe-to-top" data-toggle="modal" da ...

Python script utilizing Selenium to load only JavaScript content and excluding full HTML rendering

As I navigate through the link , I am on the lookout for the search bar marked with the class "search-field". The HTML snippet in question is as follows: from selenium import webdriver import time driver = webdriver.Firefox() driver.get("https://www.takea ...

Angular Js: Displaying JSON Object with Multiple Nested Layers

Looking for a way to display a menu using Angular and JSON object that utilizes ul and li. Trying to achieve this using ng-repeat, but encountering challenges when dealing with deeply nested objects. Here's the HTML code: <ul> <li ng-rep ...

Send pages to the holding page first before redirecting them to the appropriate page on the new website

I am in the process of updating my old website (www.old.com) with a new one that has similar pages (www.new.com). I want all the pages from www.old.com to automatically redirect to a temporary holding page (a basic html page with a countdown script and red ...

Move the divs within the overflow container by sliding them, then take out the initial element and append it to the end

Currently, when I utilize .appendTo(".wrapper") as shown in the code below, it eliminates the animation effect. My goal is to have the div on the far left slide out of view, triggering an overflow hidden effect, and then be placed at the end of the slide c ...

Having trouble implementing responsive image with fixed aspect ratio code

I've tried several tutorials online to make this image responsive with a fixed aspect ratio, but nothing seems to work. The image is set at 900x400px and I want it to remain fully visible on smaller screens as well. Here's the codepen link < ...

What is the best way to delete a container when its child element includes a specific string?

I run a website that compiles video clips from various sources, including YouTube. Occasionally, some clips appear as private videos. I am looking to use jQuery to apply the display:none; property to the entire div when the class a.colorbox.cboxElement con ...

Delay the fading in of an element using jQuery

Is there a way to remove the pause between the images in my JavaScript/jQuery slideshow when fading in and out? I attempted using a small delay, but it still didn't eliminate the blank space. Any suggestions? Check out the code on jsfiddle: https://j ...

I am seeking guidance on retrieving the value of a text box that is activated by a radio button through jquery within the provided code

When conducting my test case, the user is presented with a choice between ielts and toefl. If the user chooses ielts, an input box appears where they can enter their ielts score. My goal is to extract and store the value entered in that input box. Check ou ...

Manipulating an HTML <div> element to display its value as a suffix in another <div> within the HTML code

I'm attempting to combine and show text along with content from another <div> as the modal-header, but it's not displaying correctly. When I give an ID to the modal-header, the *&times;* symbol disappears. This is how my modal-header l ...

When the span tag is inserted into a contenteditable element on iOS Safari, the cursor automatically shifts to the

One interesting feature allows users to click on a tag and have it added to a contenteditable div. This function works smoothly initially, but when toggling back and forth, the cursor unexpectedly jumps to the end of the div. When a user adds a variable f ...

The view of the Google map is filled with numerous rounded tiles

Map divided into 3x3 tiles I am looking to customize the appearance of my map and remove all spaces and rounded corners to create a seamless, undivided visual. Is there a way to modify a map tile attribute to achieve this effect? Below is the code snippet ...

Creating a visual representation of disk status: A step-by-step guide

I am currently working on a React page and I want to create an HTML layout for displaying disk status. It would be great if there is a reusable component available for this type of chart. What is the specific name for this kind of chart so that I can searc ...

Resolving undefined errors in Angular 2 while attempting to focus on an input field with @ViewChild declaration

Upon loading my view, I typically set focus to an input field using the following method: ngAfterViewInit() { this.focusInput.nativeElement.focus(); } Everything works fine when calling it within ngAfterViewInit(). However, when attempt ...