偏移图像的边框

Offset a border over an image

我正在尝试创建与下图完全相同的内容。我也尝试过使用轮廓和偏移方法的其他方法,但我不知道如何继续这样做。

这是JSFiddle

img {
  border: 4px solid green;
}
<img src="https://image.ibb.co/cxwWPa/services_gas_oil.jpg" alt="services_gas_oil" border="0">

如何在图像上获得偏移边框?

用行内块包裹图片,并设置一个绝对定位的伪元素作为边框:

body {
  padding: 50px 0 0 80px;
}

.imageContainer {
  display: inline-block;
  position: relative;
}

.imageContainer::before {
  position: absolute;
  top: -5%;
  left: -15%;
  width: 100%;
  height: 100%;
  border: 4px solid #77B244;
  content: '';
}
<div class="imageContainer">
  <img src="https://cdn.pixabay.com/photo/2013/07/31/12/25/cat-169095_960_720.jpg" alt="services_gas_oil" border="0">
</div>

更简单的方法是结合使用边框、轮廓和底片 outline-offset。这是一个例子:

img{
  outline:4px solid #77B244;
  outline-offset:-100px;
  border:50px solid transparent;
  border-width:150px 50px 50px 150px;
  margin:-75px 0 0 -75px;
}
<img src="https://image.ibb.co/cxwWPa/services_gas_oil.jpg" alt="services_gas_oil" border="0">

这可以防止使用父元素和伪元素。

另一种可能性是将图像包裹在具有边框的 div 元素内,并将容器内的图像向左和底部移动。

Documentation开始:

A relatively positioned element is an element whose computed position value is relative. The top and bottom properties specify the vertical offset from its normal position; the left and right properties specify the horizontal offset.

我们需要将 img 包裹在像 div 这样的元素中,即:

<div class="image-holder">
  <img src="https://image.ibb.co/cxwWPa/services_gas_oil.jpg" >
</div>

我们将 border 应用到容器,并使用以下 CSS:

从其正常位置移动图像
.image-holder img {
  position: relative;
  z-index: -1;
  left: 40px;
  top: 40px;
}

.image-holder {
  border: 7px solid #76af46;
  display: inline-block;
  vertical-align: top;
}

.image-holder img {
  position: relative;
  z-index: -1;
  left: 40px;
  top: 40px;
}
<div class="image-holder">
  <img src="https://image.ibb.co/cxwWPa/services_gas_oil.jpg" alt="services_gas_oil" border="0">
</div>


或者,我们也可以使用 CSS3 translate()

.image-holder img {
  transform: translate(40px, 40px);
  position: relative;
  z-index: -1;
}

.image-holder {
  border: 7px solid #76af46;
  display: inline-block;
  vertical-align: top;
}

.image-holder img {
  transform: translate(40px, 40px);
  position: relative;
  z-index: -1;
}
<div class="image-holder">
  <img src="https://image.ibb.co/cxwWPa/services_gas_oil.jpg" alt="services_gas_oil" border="0">
</div>