Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change background on button click, using CSS only? [duplicate]

Is it possible to change the background color on button click; of the entire document, using only CSS and HTML5?

(e.g.: it's trivial in JavaScript)

like image 572
A T Avatar asked Oct 08 '13 23:10

A T


2 Answers

Based on the fiddle I posted in the comments I've modified it very slightly to use the Bootstrap button CSS.

Just include Bootstrap's CSS file then use the code below.

HTML

<label for="check" class="btn btn-default">Toggle background colour</label>
<input type="checkbox" id="check" />
<div></div>

CSS

div {
    width: 100%;
    height: 100%;
    background: #5CB85C;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 1;
}
label.btn {
    position: absolute;
    top: 10px;
    left: 10px;
    z-index: 2; 
}
input[type="checkbox"]{
    display: none;
}
input[type="checkbox"]:checked + div{
    background: #5BC0DE;
}

This uses the adjacent sibling selector.

Here it is working: http://jsfiddle.net/eYgdm/ (I've added *-user-select: none; to prevent selection of the label text but it's not required for the label to work)

Browser support

Chrome, Firefox [Desktop & Mobile] (Gecko) ≥ 1.0, Internet Explorer ≥ 7, Opera ≥ 9 and Safari ≥ 3 References: Attribute selectors and Adjacent sibling selectors

like image 135
Joe Avatar answered Oct 19 '22 00:10

Joe


You could do something like this -- using the adjacent css selector :

<button class="btn">button</button>
<div class="content"></div>

btn:active + .content{
    background: blue;
}

http://jsfiddle.net/JeffreyTaylor/g47Uh/

like image 24
Jeff Avatar answered Oct 19 '22 00:10

Jeff