简体   繁体   English

HTML CSS:切换/更改div的背景颜色,单选按钮选择时标签文本的颜色

[英]HTML CSS: Switch/Change background color of div, color of label text on radio button selection

I have input and label inside a div. 我在div中有输入和标签。 There are two divs div1 and div2. 有两个div div1和div2。 I want to change background color of div and color of label text when selecting corresponding radio button. 选择相应的单选按钮时,我想更改div的背景色和标签文本的颜色。

Div color want to change from red to blue div颜色要从红色变为蓝色

label text color black to yellow 标签文字颜色黑色黄色

I have written below HTML and CSS for this: 我为此编写了以下HTML和CSS:

HTML: HTML:

<div class="main_div">
    <div class="div1">
        <input type="radio" name="group1" value="1" id="yes" /><label for="yes">Yes, It is</label>
    </div>
    <div class="spaceDiv"></div>
    <div class="div2">
        <input type="radio" name="group1" value="2" id="no" /><label for="no">Not at all</label>
    </div>
</div>

CSS: CSS:

.div1, .div2 {
    background: red;
    display: block;
    height: 3em;

}

.div1, .div2 input {
    padding: 1em;
}

.div2, .div1 input {
    padding: 1em;
}

.div1 label {
    padding: .9em;
}

.div2 label {
    padding: .9em;
}


.spaceDiv {
    background: #fff;
    height: 0.5em;
}

Here's a solution, which uses the :after pseudo-element on the label so it covers the entire div . 这是一个解决方案,它在label上使用:after伪元素,以便覆盖整个div The background has been moved from the div to this pseudo-element. 背景已从div移至该伪元素。 When the input is checked, the general sibling selector (~) is used to change the background color of the pseudo-element as well as the text color of the label . 选中input ,将使用通用的同级选择器 (〜)更改伪元素的背景颜色以及label的文本颜色。

how I can vertical align input and label inside the div? 如何在div中垂直对齐输入和标签? I have used padding stuff which is not correct 我使用了不正确的填充材料

Since there's only one line of text, setting line-height equal to height will cause vertical alignment. 由于只有一行文本,因此将line-height设置为height会导致垂直对齐。 You can then remove the padding: 然后,您可以删除填充:

.div1,
.div2 {
  height: 3em;
  line-height: 3em;
}

Snippet: 片段:

 .div1, .div2 { display: block; height: 3em; line-height: 3em; position: relative; } .spaceDiv { background: #fff; height: 0.5em; } label:after { content: ''; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: red; z-index: -1; } input:checked ~ label:after { background: blue; } input:checked ~ label { color: yellow; } 
 <div class="main_div"> <div class="div1"> <input type="radio" name="group1" value="1" id="yes" /> <label for="yes">Yes, It is</label> </div> <div class="spaceDiv"></div> <div class="div2"> <input type="radio" name="group1" value="2" id="no" /> <label for="no">Not at all</label> </div> </div> 

http://jsfiddle.net/mwbbcyja/58/ http://jsfiddle.net/mwbbcyja/58/

input:checked + label {
    background-color:red;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM