James
James

Reputation: 1925

How to use css focus?

I am familiar with using css and the 'hover' feature but I am interested in knowing how to use an on click feature.

So to begin with to use the hover feature you can have:

#test {
background: black;
height: 100px;
width: 100px;
}

and then when the mouse 'hovers' over I want it to turn white

#test:hover {
background: white;
height: 100px;
width: 100px;
}

So is the a similar way of changing the background on click?

Thanks!

James

Upvotes: 0

Views: 1355

Answers (3)

Kyle
Kyle

Reputation: 67244

The psuedo selector element:focus is used generally for when an element has focus. Like when you are typing inside a textarea or input.

As you can see in this demo, button:focus doesn't make the background-color any different onClick.

To make it change while being clicked, use the element:active pseudo selector:

button:active
{
    background-color: #f00;
}

Working demo here.

Upvotes: 3

Álvaro González
Álvaro González

Reputation: 146640

Your description is slightly vague but current CSS specs only provide the following related pseudo-classes:

  • :active - Applies briefly while the element is being clicked
  • :focus - Applies while the element is focused (mouse or not)

Upvotes: 0

Jason Gennaro
Jason Gennaro

Reputation: 34863

So is the a similar way of changing the background on click?

You can use javascript for this.

Simpliest thing is to use some jquery

$('#test').click(function(){
    css('background','green');
});

You can also change the class of an item once clicked. This way you can store the css in your styelsheet.

$('#test').click(function(){
    $(this).addClass('greenBackground');
});

Upvotes: 0

Related Questions