5

I want to add a border to div on hover, but the div shit slightly when the border is added. It is a well-known problem, and the common solution is to add a transparent border. (For example) However, I have an image with some text in my div and I want the image to take full width of the div. Adding a transparent border will makes the background color shows up and not taking the full width.

HTML:

<div class="outer-container">
  <div class="inner-container" contenteditable="true">
    <img src="./testing.png">
    some other text
  </div>
</div>

CSS:

.outer-container {
  width: 100%;
  background: #000000
}
.inner-container {
  margin: auto;
  width: 300px;
  margin-bottom: 0px;
  background: #FF0000;
  border: 1px solid transparent;
}
.inner-container:hover {
  border: 1px solid blue;
}

jsfiddle for demo

The height of the div is variable in actual use as it is to be uploaded by user. I know I can solve the problem with javascript, but is there a way I can make the desired effect with CSS only?

Community
  • 1
  • 1
cytsunny
  • 4,838
  • 15
  • 62
  • 129

1 Answers1

9

You can simply fix this with outline property

.inner-container:hover {
  outline: 1px solid blue;
 }

and if you are using big border eg: set outline:3px; solid blue; then use outline-offset:-3px;

try with demo

https://jsfiddle.net/be7441LL/2/

Jishnu V S
  • 8,164
  • 7
  • 27
  • 57
  • 1
    Wow, I just done some research and found that it is supported since IE8..... can't believe people still tell other to use border. – cytsunny Jan 25 '17 at 09:05
  • 1
    This is doesn't work if you have a div with the border-radius set. "Outline differs from borders! Unlike border, the outline is drawn outside the element's border, and may overlap other content. Also, the outline is NOT a part of the element's dimensions; the element's total width and height is not affected by the width of the outline." – Morema Nov 18 '20 at 17:17