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

标签 html css

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

如您所见,蓝色边框的所有边都有不同的长度。我怎样才能制作这样的边框?

最佳答案

如果不在 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>

关于html - 如何使用CSS在图像周围创建不对称边框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52272019/

相关文章:

javascript - ASP.NET JQuery 从文本框值过滤列表框(区分大小写的问题)

javascript - 为什么 if/then 对于 document.querySelector 不起作用?剪刀石头布游戏的部分代码

html - 如何在 Firefox 和 Internet Explorer 中包含 css 字体?

html - 如何将我的文本和输入框对齐在同一行?

html - 缩小时过大的图像模糊

css - Selenium Webdriver C#::CSS 选择器在 Internet Explorer 中无法正常工作

jquery - Bootstrap 表单验证

html - 带条件的 CSS 属性

javascript - 在 iOS 上运行 Node.js 作为服务器并让其他设备连接进来

javascript - 在 contenteditable div 内的 span 元素之后设置光标