实现 0.5 px的边框一共可以分为两种情况:
1. 单边框
主要有以下方法:
- border + border-image + linear-gradient
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.border {
width: 200px;
height: 200px;
background-color: red;
margin: 0 auto;
border-bottom: 1px solid transparent;
border-image: linear-gradient(to bottom,transparent 50%,green 50%) 0 0 100% 0;
}
</style>
</head>
<body>
<div class="border"></div>
</body>
</html>
2. 伪元素 + background-image
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style type="text/css">
.border {
width: 200px;
height: 200px;
background-color: red;
margin: 0 auto;
position: relative;
}
.border::before {
content: "";
position: absolute;
left: 0;
bottom: 0;
width: 100%;
height: 1px;
background-image: linear-gradient(to bottom,transparent 50%,blue 50%);
}
</style>
</head>
<body>
<div class="border"></div>
</body>
</html>
- 定位 + 伪元素 + transform缩放(scale)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.border {
width: 200px;
height: 200px;
margin: 0 auto;
background-color: red;
position: relative;
}
.border::before {
content: "";
position: absolute;
left: 0;
bottom: 0;
width: 100%;
height: 1px;
background-color: blue;
/* 注意是Y轴方向缩小一半 */
transform: scaleY(0.5);
}
</style>
</head>
<body>
<div class="border">
</div>
</body>
</html>
2. 多边框
- 定位 + 伪元素 + transform缩放(scale)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.border {
width:200px;
height: 200px;
background-color: red;
margin: 0 auto;
position: relative;
}
.border::before {
content: "";
position: absolute;
left:0;
top: 0;
width: 200%;
height: 200%;
border: 1px solid blue;
/* 以(0,0)为放缩中心点 */
transform-origin: 0 0;
/* 缩小一半 */
transform: scale(0.5);
}
</style>
</head>
<body>
<!-- 多边框 -->
<div class="border"></div>
</body>
</html>