Choose the label by utilizing the CSS selector

I am currently using CSS to create tabs with radio buttons. However, I am struggling to figure out how to select the corresponding <label> for the radio button. To keep the labels separate from the content and display them as tabs, I have structured them as follows:

<div class="tab-labels">
   <label for="tab-1">Tab 1</label>
   <label for="tab-2">Tab 2</label>
   <label for="tab-3">Tab 3</label>
</div>

The content panes are positioned below. The radio input button is placed inside the content div so that it can be selected when the label is clicked. Unfortunately, I am unable to achieve this in reverse order:

<div class="content-container">
    <div class="tab details">
        <input id="tab-1" type="radio" name="radio-set" class="tab-selector" checked="checked"/>
        <div class="content">
            <p>Some content 1</p>                   
        </div>
    </div>
    <div class="tab details">
        <input id="tab-2" type="radio" name="radio-set" class="tab-selector"/>
        <div class="content">
            <p>Some content 2</p>                   
        </div>
    </div>
    <div class="tab details">
        <input id="tab-3" type="radio" name="radio-set" class="tab-selector"/>
        <div class="content">
            <p>Some content 3</p>                    
        </div>
    </div>
</div>

My main goal and question regarding this issue is: How can I change the background color of the label when the radio input is clicked based on this structure?

If you would like to experiment with this setup live, I have provided a fiddle link: http://jsfiddle.net/mjohnsonco/6KeTR/

Answer №1

To accomplish this task using only CSS, it would require restructuring the HTML and writing some rather confusing CSS code.

Take a look at this example: http://jsfiddle.net/kizu/6KeTR/16/

In this example, you will need to move all the input elements outside of their containers to a specific location where they can directly affect the blocks you want them to target. This allows you to then select the parent elements of the tabs and their content using the ~ combinator along with nth-child selectors like so:

#tab-1:checked ~ .content-container > .tab:first-child  > .content,
#tab-2:checked ~ .content-container > .tab:nth-child(2) > .content,
#tab-3:checked ~ .content-container > .tab:nth-child(3) > .content {}

However, these CSS-only solutions are more of a proof-of-concept than practical solutions. They may not be as maintainable or user-friendly as their JavaScript counterparts. It's best to use them just for experimentation or learning purposes :)

Answer №2

Cascading Style Sheets

.style1{

background-color:#blue;

}
.style2{

background-color:green;

}
.style3{

background-color:red;

}

jQuery

$('input[name=radio-set1]:checked', '#main').addClass(style1)

$('input[name=radio-set2]:checked', '#main').addClass(style2)

$('input[name=radio-set5]:checked', '#main').addClass(style3)

HyperText Markup Language

 <input id="tab-1" type="radio" name="radio-set1" class="tab-selector" checked="checked"/>
 <input id="tab-2" type="radio" name="radio-set2" class="tab-selector" checked="checked"/>
 <input id="tab-3" type="radio" name="radio-set3" class="tab-selector" checked="checked"/>

<label class="style1" for="tab-1">Tab 1</label>
<label class="style2" for="tab-2">Tab 2</label>
<label class="style3" for="tab-3">Tab 3</label>

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 appearance of an element based on user selection from a dropdown menu under certain circumstances

I am working on creating a dropdown menu using a JavaScript array. My goal is to display a specific span element when certain options are selected. For instance, I want the span to be shown only when options "a" and "c" are selected, but not when option " ...

Can CSS be used to communicate to JavaScript which media queries are currently in effect?

Is there a way for Javascript to detect when a specific CSS media query is active without repeating the conditions of the media query in Javascript? Perhaps something similar to an HTML data attribute, but for CSS. For example: CSS @media (min-width: 94 ...

Disabled screen rotation -> hidden background

I tried implementing a media query to "lock" the orientation on my mobile site, but unfortunately, my background image isn't displaying at all. After adding the media query, I included my stylesheet using the link: CSS body { padding:0; marg ...

The Jquery slider panel seems to be stuck open even after I switched its CSS orientation from right to left

I am following up on a previous question, which can be found here. After fixing the jQuery code, I decided to change the panel slider to open from the left side instead of the right. I modified the class from "cd-panel from-right" to "cd-panel from-left". ...

Transfer information to a different html page and store it

Seeking guidance on transferring the entire content of input.html to approve.html for validation and database storage. Any tips or advice would be greatly appreciated as I am new to this and have been struggling with this issue for a week. <form action= ...

The dropdown menus in Bootstrap are expanding outside the screen when opened

When I click on the dropdown in the Navbar on the right side, the menus open up far to the right and are not visible until I scroll horizontally. Here is the code snippet: <nav class="navbar navbar-expand-lg navbar-light bg-light"> < ...

Flexbox mystery: How come the entire div isn't displayed when the element below it is hidden?

I am in need of a versatile column layout where multiple widgets are stacked vertically, adjusting their size dynamically. Each widget consists of a title and scrollable content. The last widget should have the ability to collapse when its title is clicked ...

What factors contribute to the poorer performance of SVG rendering compared to PNG rendering?

I conducted a comparison of two images across various browsers. One image is an SVG while the other is a PNG format. Here are my findings: You can view the demo on JSFiddle here: http://jsfiddle.net/confile/2LL5M/ This is the code snippet I utilized: ...

Java Applet for capturing specific sections of a webpage to create a screenshot

Does anyone know of a way (applet or something else) to capture a screenshot of the content within a specific div on a webpage? I came across this Java code for capturing a screenshot of the entire screen: import java.awt.AWTException; import java.awt.Re ...

Using JavaScript to empty input field when switching focus between input fields

I am experiencing an issue with clearing a input number field. Here is the code snippet in question: <input class="quantity_container" v-model="length.quantity" type="number" pattern="[0-9]*" inputmode="numeric" onfocus="if (this.value == &ap ...

Reorganize containers without relying on bootstrap styling

Is there a method to rearrange the order of two divs without using the bootstrap library? <div class='parent'> <div class='child-1'>Abc..</div> <div class='child-2'>Xyz..</div> </div> I ...

Concealing a hyperlink within a DIV by removing or hiding it

I am looking to temporarily hide or remove a specific link (team.aspx) within a drop-down menu, with the intention of adding it back in later. Here is my current code: <div id="nav_menu"> <ul id="nav"> <li class="current"><a href= ...

Get the content from a webpage, find and calculate the total count of div elements with a specific class, and display that number

Greetings everyone, I've run into a bit of a roadblock. My goal is to create a basic script that can count the number of servers currently running on this map by scraping the webpage, calculating the divs with the class ".row ark_srv1", and then displ ...

Popup window displaying website content upon DOM loading, ensuring compatibility across various browsers

I am facing a challenge with my HTML popup window where I need to add text after opening the window using a specific function: var win = window.open('private.php', data.sender_id , 'width=300,height=400'); win.win ...

Unable to place an absolutely positioned Div within relative parent containers

After applying the id "enterGame" with position: absolute, I noticed that the div disappears. Even when I tried adding position: relative to the body or html tag, the div remained invisible. The relevant code snippet is as follows: html { height: 10 ...

Using HTML and JavaScript allows for the video URL to seamlessly open in the default video player app on the device

Working on my mediaplayer website, I want to give users the option to choose which app to play their uploaded videos with. So far, I've attempted to implement a button that triggers this action: window.open("video.mkv", '_blank'); Howeve ...

Utilize jQuery to trigger video playback based on the horizontal movement of the mouse

Utilizing this jQuery script to navigate back and forth in a video as the cursor moves along the x-axis. var mouseX; $(document).mousemove( function moveFunc(e) { mouseX = e.clientX; var timV = $("#deko_vid").get(0).duration; var valV = (timV*mouseX/$(do ...

Customize the background based on the user's choice

Hello, I'm interested in having 5 different backgrounds for users to choose from. I want them to be able to click on a thumbnail and have the site's background change dynamically. Could you please advise me on how to achieve this? Thank you for a ...

Allow iframe to be edited within jsfiddle

I have a question that I need to ask soon, but first I need an editable iframe in jsfiddle. It's working fine on my local machine, but not on jsfiddle. I believe it's because of the frames being used? On my local machine, I use: setTimeout(&apo ...

Ways to retrieve various data elements from ajax using PHP

Can you help me with my AJAX code that retrieves data from a PHP script? I want to know how to set multiple echo variables in PHP and display them separately using AJAX without reloading the page. AJAX Code $(document).ready(function() { //el ...