图像顶部的内边框

Inner Border on the top of the image

我正在尝试在鼠标悬停时为图像添加上边框。边框应该出现在图像的顶部(我的意思是在顶部的图像内部)并且它不应该为图像的宽度添加额外的像素。

下图代表了我想要实现的效果:左图 - 无边框图像,右图,带边框的图像位于图像顶部

我尝试使用悬停添加边框,但在 img 标签上悬停 - 边框被添加到图像 - 然后图像的宽度更大。

'box-sizing' 属性 在这里很重要,以确保它不会将边距大小添加到 div 本身,而是在 'inside' 上,如果你愿意的话.

.image {
  width:200px;
  height:200px;
  float:left;
  background:black;
  margin:10px;
  box-sizing:border-box;
  position:relative;
}
.image img {
  width:100%;
  float:left;
}
.image:hover .overlay {
  border-top:4px solid red;
}

.overlay {
  width:100%;
  position:absolute;
  top:0;
  left:0;
}
<div class="image">
  <div class="overlay"></div>
  <img src="https://cdn.pixabay.com/photo/2017/01/06/23/21/soap-bubble-1959327_1280.jpg"/>
</div>
<div class="image">
  <div class="overlay"></div>
  <img src="https://cdn.pixabay.com/photo/2017/01/06/23/21/soap-bubble-1959327_1280.jpg"/>
</div>

您可以在 css

中添加此代码
    .image {
      width:200px;
      height:200px;
      float:left;
      background:black;
      margin:10px;
      box-sizing:border-box;
      position:relative;
    }
    .image:before {
      content:'';
      opacity:0;     
}
    .image:hover:before {
      position:absolute;
      height:5px;
      width:100%;
      top:0px;
      background:red;
      z-index:100;
      content:'';
      -webkit-transition:all .5s;
      opacity:1;
    }
<div class="image"></div>

这还是有可能的。查看下面 fiddle link 中的代码并尝试这样的操作:

HTML

<div class="image-container">
  <div class="top-border"></div>
  <img src="yourimagehere">
</div>

CSS

.image-container {
  position:relative;
  width:225px;
  height:225px;
}

.top-border {
  width:100%;
  height:10px;
  background:green;
  position:absolute;
  display:none;
}

.image-container:hover .top-border {
  display:block
}

https://jsfiddle.net/4k52y5kc/5/

如果图像大小已知并且可以在 CSS 中 (re) 设置,object-fit & object-position 可能是达到预期效果的一种方式。

img:hover {
  border-top:solid red 15px;
  box-sizing:border-box;
  object-fit:cover;
  object-position:bottom left;
  height:275px;
  width:500px;
<img src="http://lorempixel.com/500/275/food/7" alt="bread"/>