在悬停时添加边框时如何防止移动? (透明边框不是解决方案) [英] How to prevent shifting when adding border on hover? (Transparent border is not a solution)

查看:73
本文介绍了在悬停时添加边框时如何防止移动? (透明边框不是解决方案)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在悬停时向div添加边框,但是在添加边框时div会稍微变糟。这是一个众所周知的问题,常见的解决方案是添加透明边框。 (例如, )但是,我的div中有一个带有一些文本的图片,我希望该图片的宽度为div。添加透明边框将使背景颜色显示出来,而不会占据整个宽度。

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

div的高度在实际使用中是可变的,因为它是由用户上传的。我知道我可以用javascript解决问题,但是有什么办法可以只用CSS达到预期的效果?

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?

推荐答案

您只需使用 outline 属性

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

,如果您使用大边框
,例如:
设置为 outline:3px;蓝色; 然后使用 outline-offset:-3px;

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

尝试演示

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

这篇关于在悬停时添加边框时如何防止移动? (透明边框不是解决方案)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆