11

手机上如何实现细/1px/0.5px边框

 3 years ago
source link: https://zhuanlan.zhihu.com/p/340711204
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

手机上如何实现细/1px/0.5px边框

饥人谷前端,培养有灵魂的前端工程师

简述

有几种方法能实现0.5px边框:

  1. 直接设置 border-width: 0.5px;使用方便,但兼容性很差,不推荐使用。
  2. 用阴影代替边框,设置阴影box-shadow: 0 0 0 .5px #000; 使用方便,能正常展示圆角,兼容性一般。
  3. 给容器设置伪元素,设置绝对定位,高度为1px,背景图为线性渐变,一半有颜色,一半透明。视觉上宽度只有0.5px。这种方法适合设置一条边框,没法展示圆角。
  4. 给容器内设置伪元素,设置绝对定位,宽、高是200%,边框是1px,然后使用transform: scale(0.5) 让伪元素缩小原来的一半,这时候伪元素的边框和容器的边缘重合,视觉上宽度只有0.5px。这种方法兼容性最好,4个边框都能一次性设置,能正常展示圆角,推荐使用

代码测试

做移动端开发的时候,如果边框直接设置 1px的宽度,可能视觉上还是太粗无法满足设计师的要求。下面是实现0.5px边框的几种方案。推荐方案4,复杂度中等,扩展性良好,兼容性好。

<div class="box box1"> 1px 边框,作为对比 </div>
<div class="box box2"> 方案1: 直接设置0.5px边框</div>
<div class="box box3"> 方案2: 设置0.5px阴影扩散半径 </div>
<div class="box box4"> 方案3: 使用背景渐变实现1px背景的一半</div>
<div class="box box5"> 方案4: 伪元素2倍尺寸1px边框scale缩小一半</div>
<style>
  .box {
  width: 200px;
  height: 50px;
  border-radius: 10px;
  margin-top: 10px;
}
.box1 {
  border: 1px solid #000;
}
.box2 {
  border: 0.5px solid #000;
}
.box3 {
  box-shadow: 0px 0px 0px 0.5px #000;
}
.box4 {
  position: relative;
}
.box4::after {
  content: "";
  position: absolute;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 1px;
  background-image: linear-gradient(0deg, #000 50%, transparent 50%);
}
.box5 {
  position: relative;
}
.box5::after {
  position: absolute;
  bottom: 0;
  z-index: -1;
  width: 200%;
  height: 200%;
  content: "";
  display: block;
  border: 1px solid #000;
  border-radius: 10px;
  transform: scale(0.5);
  transform-origin: left bottom;
}
</style>

在文章底部查看代码动手测试。

感谢

  • 最近的文章为前端剑指offer系列,是面向大厂求职的文章合集,可以点击阅读原文查看往期文章。关注公众号「 编程公子 」不错过每一次更新,回复 2 加小助手微信,进前端大厂面试刷题群和其他小伙伴一起分享讨论,也能加作者微信一起交流。
发布于 6 小时前

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK