Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent shifting when adding border on hover? (Transparent border is not a solution)

Tags:

html

css

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?

like image 368
cytsunny Avatar asked Mar 10 '23 01:03

cytsunny


1 Answers

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/

like image 77
Jishnu V S Avatar answered Apr 24 '23 22:04

Jishnu V S