14

I have below code in html page:

<img id="image_java"  alt="image_not" src="images/java-icon.png">

in css page the below code:

#image_java: focus {
outline: 2px solid blue;
}

I have also tried:

img:focus{
outline: 2px solid blue;

}

but non of them seem to work, they are suppose to display a blue margin around the image when focus. Does any one know how to do that? thank you!!!

MauricioTL
  • 343
  • 1
  • 5
  • 17

4 Answers4

43

Actually you CAN focus an <img> - with the help of tabindex:

img:focus {
    outline: 2px solid blue;
}
<img src="http://www.w3schools.com/images/w3logotest2.png" tabindex="0">
Leo
  • 13,428
  • 5
  • 43
  • 61
  • 3
    This should be accepted answer. Also refer to http://stackoverflow.com/questions/3656467/is-it-possible-to-focus-on-a-div-using-javascript-focus-function (div and img are not that different in terms of focus). – Christian Fritz Jan 06 '17 at 23:57
  • Also add a keyboard event handler to the img element. – Edward Dec 11 '19 at 15:23
13

You can't "focus" an image unless you have an interactive element or navigate to it using tab. Try adding an interactive element on a wrapper div like so:

Html

<a class="imageAnchor" href="#">
    <img id="image_java" alt="image_not" src="http://www.w3schools.com/images/w3logotest2.png" />
</a>

CSS

.imageAnchor:focus img{
    border: 2px solid blue;
}

http://jsfiddle.net/4x7wg7sb/1/

ryanlutgen
  • 2,951
  • 1
  • 21
  • 31
1

If its an anchor tag you can also use

A:focus img{border: 2px solid blue;}

-5

Try using the border property instead of the outline property. It should look like:

img:hover {
    border: 2px solid blue;
}

Edit: Use hover instead of focus