Agargara
Agargara

Reputation: 932

How can I add a 1px border to an image without a gap?

I would like to draw a border around an image with no visible gap between the image and the border.

img{
  display: block;
  border: 1px solid black;
}
<img src="https://files.catbox.moe/r099uw.png">

Result of above snippet in Chrome (Version 84):
result of above snippet

There is a small gap between the image and the border to the right and below the image.

The answer to this similar question suggests setting display: block on the image, but this does not seem to solve the problem in this case. Based on other answers I have also tried vertical-align:bottom, padding:0, margin: 0; adding width/height, but all to no avail. Increasing the border to 2px gets rid of the gap, but is not an ideal solution.

I tested the above snippet in Chrome, Firefox, and Microsoft Edge. It displays without a gap in Firefox, but with a gap in Chrome and Edge.

How can I create a bordered image that displays consistently without a gap across all platforms?

Upvotes: 0

Views: 916

Answers (3)

Vladyslav Topchii
Vladyslav Topchii

Reputation: 50

try this:

img {
   outline: 1px solid black;
}
<img src="https://files.catbox.moe/r099uw.png">

Also, if necessary, try to append outline-offset, like outline-offset: -1px;

Upvotes: 0

CODAR747
CODAR747

Reputation: 174

You can fix this with css styling. This is what we can do, let's define a css class or id with desired width and height that you would like to have for image. Now use your image as background for defined div or class. Stroke/Border effect can be done by giving border to defined class or id. Once you're done you can adjust your image by making some changes to background-size. That will make you image zoom in or zoom out. So you can easily cover up the gap for any image. Here is the code

HTML :

<div id="image"> </div>

CSS :

#image {
display:inline-block;
width:30px;
height:30px;
border:1px solid #000;
background-image:url(TOn2E.png);
background-repeat:no-repeat;
background-position: center;
background-size: 150%
}

For adjusting image you can make changes to background-size in percentage.

Upvotes: 0

Agargara
Agargara

Reputation: 932

It appears that adding box-sizing: border-box; as well as a specific height solves the problem in Chrome and Edge.

img{
  border: 1px solid black;
  height: 16px;
  box-sizing: border-box;
}
<img src="https://files.catbox.moe/r099uw.png">

If anybody knows a better solution, or why this is necessary, please let me know.

Edit: This solution is not perfect, as the gap can reappear depending on the position of the image. For example:

img{
  border: 1px solid black;
  height: 16px;
  width: 16px;
  box-sizing: border-box;
  position: relative;
  left: 1px;
}

span{
  border: 1px solid red;
}
<span>
<img src="https://files.catbox.moe/r099uw.png">
</span>

Result in Chrome (zoomed in for detail): enter image description here

Upvotes: 1

Related Questions