如何使用css在图像周围创建不对称边框?

时间:2018-09-11 08:42:40

标签: html css

所以我有一个图像,我想在其周围创建边框。边框的每一边我都希望其长度不同。这是我要实现的目标(蓝色边框): enter image description here

如您所见,蓝色边框的两侧各有不同的长度。我怎么做这样的边界?

2 个答案:

答案 0 :(得分:1)

如果不在img周围添加几个额外的容器元素,我想不出一种方法。

这可能会使您接近想要的效果...

.container {
  text-align: right;
  position: relative;
  padding: 20px;
  overflow: hidden;
}

.shrinkwrap {
  float: right; /* Shrink to fit img */
  position: relative;
}

.container img {
  display: block; /* Remove bottom spacing */
}

/* Top/Right border */
.container::before {
  content: "";
  position: absolute;
  top: 10px;
  right: 10px;
  bottom: 10px;
  left: 0;
  border-top: 1px solid blue;
  border-right: 1px solid blue;
}

/* Bottom/Left border */
.shrinkwrap::before {
  content: "";
  position: absolute;
  top: 50%;
  right: -10px;
  bottom: -10px;
  left: -10px;
  border-bottom: 1px solid blue;
  border-left: 1px solid blue;
}
<div class="container">
  <div class="shrinkwrap">
    <img src="https://placehold.it/300x300">
  </div> 
</div>

它适用于任何尺寸的图像。

如果您在.shrinkwrap元素上使用基于百分比的尺寸,则可以使其具有响应性...

.container {
  text-align: right;
  position: relative;
  padding: 20px;
  overflow: hidden;
}

.shrinkwrap {
  float: right; /* Shrink to fit img */
  position: relative;
  width: 50%;
}

.container img {
  display: block; /* Remove bottom spacing */
  width: 100%;
}

/* Top/Right border */
.container::before {
  content: "";
  position: absolute;
  top: 10px;
  right: 10px;
  bottom: 10px;
  left: 0;
  border-top: 1px solid blue;
  border-right: 1px solid blue;
}

/* Bottom/Left border */
.shrinkwrap::before {
  content: "";
  position: absolute;
  top: 50%;
  right: -10px;
  bottom: -10px;
  left: -10px;
  border-bottom: 1px solid blue;
  border-left: 1px solid blue;
}
<div class="container">
  <div class="shrinkwrap">
    <img src="https://placehold.it/300x300">
  </div> 
</div>

答案 1 :(得分:0)

您可以在图像的不同容器上使用“之后”和“之前”来创建这种效果。

https://jsfiddle.net/theylooksotired/w0s4xmc0/42395/

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

.image:after {
  position: absolute;
  content: '';
  width: 80%;
  height: 1px;
  background: red;
  bottom: -5px;
  right: 0;
}

.image:before {
  position: absolute;
  content: '';
  width: 1px;
  height: 100%;
  background: blue;
  top: -5px;
  right: 0;
}
<div class="image">
  <img src="http://dazedimg.dazedgroup.netdna-cdn.com/1112/azure/dazed-prod/1150/1/1151968.jpg" width="200" height="130" />
</div>