Outline applied to an anchor containing an image i

2019-03-31 06:10发布

问题:

For a site I'm working on, I'd like to have a dotted outline appear around links when they are focused/hovered/active. I'd like this to happen for text and image links.

The issue I have is that whilst my code works great in Firefox and IE, in Chrome 7.0.517.41 the dotted outline is the same height as my text, not the height of the image.

Sample code:

<!DOCTYPE html> 
<html lang="en"> 
    <head>
        <style type="text/css">
            BODY { font: 15px/1.5 sans-serif; }
            a:focus, a:hover, a:active { outline: 1px dotted #11aa22; }
        </style>
    </head>
    <body>
        <a href="#">
            <img src="http://sstatic.net/stackoverflow/Img/wmd-buttons.png" />
        </a>
    </body>
</html>

This is annoying. As a workaround I use javascript to apply a class to distinguish anchors containing images, and ensure that the outline for anchors containing images is applied to the anchor, not the image:

a:focus, a:hover, a:active { outline: 1px dotted #11aa22; }
a:focus.img, a:hover.img, a:active.img { outline: none; }
a:focus img, a:hover img, a:active img { outline: 1px dotted #11aa22; }

And in my document ready

$('a:has(img)').addClass('img');

Is there a better way to do this?

回答1:

You have to set links as blocks for they wrap images, as

a { display:inline-block; }

eg.