Change div background color on click using only css

时间:2022-11-20 13:58:44

So I have a div I want to change the color of when clicked. I have three divs over all and I want to denote which one is the active div when clicking on it

所以我有一个div我想改变点击时的颜色。我有三个div,我想在点击它时表示哪一个是活动div

Basically I want to use the CSS active property but not have the particular div change back when the mouse up occurs. Sort of like a focus. I am also using bootstrap if that is helpful

基本上我想使用CSS活动属性,但是当鼠标向上发生时没有特定的div更改。有点像焦点。我也在使用bootstrap,如果这有用的话

Here is a example of the html

这是html的一个例子

<div>
    Section 1
</div>
<div>
    Section 2
</div>
<div>
    Section 3
</div>

Could anyone tell me how i could accomplish this without using javascript?

谁能告诉我如何在不使用javascript的情况下实现这一目标?

3 个解决方案

#1


21  

Make your DIVs focusable, by adding tabIndex:

通过添加tabIndex使您的DIV可聚焦:

<div tabindex="1">
Section 1
</div>

<div tabindex="2">
Section 2
</div>

<div tabindex="3">
Section 3
</div>

Then you can simple use :focus pseudo-class

然后你可以简单地使用:focus伪类

div:focus {
    background-color:red;
}

Demo: http://jsfiddle.net/mwbbcyja/

#2


-2  

div:focus {
    background-color:'color';
}

#3


-4  

Try Using this

尝试使用此功能

div .active {
    background-color:blue;
    }

#1


21  

Make your DIVs focusable, by adding tabIndex:

通过添加tabIndex使您的DIV可聚焦:

<div tabindex="1">
Section 1
</div>

<div tabindex="2">
Section 2
</div>

<div tabindex="3">
Section 3
</div>

Then you can simple use :focus pseudo-class

然后你可以简单地使用:focus伪类

div:focus {
    background-color:red;
}

Demo: http://jsfiddle.net/mwbbcyja/

#2


-2  

div:focus {
    background-color:'color';
}

#3


-4  

Try Using this

尝试使用此功能

div .active {
    background-color:blue;
    }