Artemix
Artemix

Reputation: 8655

How to add a hover border to an image inside the IMG tag?

I want to add a hover border to an image, but I want/need to do it inside the same tag, since I'm dong it in Wordpress and I have no idea how to link the class.

So in other words, I need to do everything inside the style inside the img tag.

So far all the examples I've found are about linking external classes.

This is inside a Wordpress page btw.

Upvotes: 0

Views: 2227

Answers (3)

T. Ruck
T. Ruck

Reputation: 3

<img src="your-image-file-path-here.jpg" style="padding:5px;border-radius:7px;" onmouseover="this.style.backgroundColor='red'" onmouseout="this.style.backgroundColor='white'" />

There are four critical styles applied here:

  1. Padding, keeps a background area five pixels wide around the image, so we can change that background color on hover.
  2. Mouseover: changes the background color of the padding space.
  3. Mouseout: changes the bg color back again when the cursor moves off the image.
  4. Border-radius: rounds the corners of the hover border.

El Magnifico is right. You can't use a pseudo class or css:hover inline.

You can change the background color to whatever matches your theme or remove it altogether. You can change the padding. Just be sure to keep a fixed padding size of at least 1px specified for the image and this should work. Adding and deleting a css:border with the mouse events may cause the image to move. This is why I suggested you add padding and change the background color instead of adding a border.

I tested this. Let me know if it works for you.

Upvotes: 0

Desmond
Desmond

Reputation: 1736

EDIT: Just re-read your post and realised you want inline styling. If you want to add CSS to your page and use a class, look for the style.css file inside your Wordpress theme.

Here's the example if you do it the class way:

To have the border appear inside the image and not outside, you could try box-sizing: border-box

img {
    box-sizing: border-box;
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
}

img:hover {
    border: 20px solid red;
}

If this doesn't work how you want it, you could add a border to the image that blends into the background. So for example, if you had a white background, add a 5px white border to the image and just change the colour on hover.

img {
    border: 20px solid white;
}

img:hover {
    border-color: red;
}

Without seeing your code I can't be too specific, hopefully this is of some help.

Upvotes: 1

El Magnifico
El Magnifico

Reputation: 31

You can't use a pseudo class inside an html tag; I think that this is not recommended but if you have to you could use JS

<img onmouseover="this.style.border = '1px solid #123456'" onmouseout="this.style.border = '0px'" src="yourImg.png">

Upvotes: 0

Related Questions