เส้นขอบแบบไล่ระดับสีช่วยเพิ่มสัมผัสที่ทันสมัยและดึงดูดสายตาให้กับองค์ประกอบเว็บ ทำให้องค์ประกอบเหล่านั้นโดดเด่น อย่างไรก็ตาม การบรรลุผลนี้ใน CSS ไม่ใช่เรื่องตรงไปตรงมาเพราะ 05 คุณสมบัติไม่รองรับการไล่ระดับสี บทความนี้จะสำรวจวิธีแก้ปัญหาเชิงปฏิบัติเพื่อใช้เส้นขอบไล่ระดับสีโดยใช้วิธีการที่แตกต่างกันสามวิธี
ไวยากรณ์
/* Method 1: Using border-image */
selector {
border-width: 5px;
border-style: solid;
border-image: linear-gradient(direction, color1, color2) 1;
}
/* Method 2: Background and Padding */
.parent {
background: linear-gradient(direction, color1, color2);
padding: border-width;
}
/* Method 3: Pseudo-elements */
selector::before {
content: "";
position: absolute;
inset: -border-width;
background: linear-gradient(direction, color1, color2);
z-index: -1;
}
วิธีที่ 1:การใช้ border-image
15รหัส> คุณสมบัติช่วยให้คุณสามารถตั้งค่าการไล่ระดับสีเป็นเส้นขอบขององค์ประกอบ
<!DOCTYPE html>
<html>
<head>
<style>
.gradient-border-box {
width: 300px;
padding: 20px;
text-align: center;
border-width: 5px;
border-style: solid;
border-image: linear-gradient(to right, #ff6b6b, #4ecdc4) 1;
margin: 20px auto;
}
</style>
</head>
<body>
<div class="gradient-border-box">
This is a gradient border using border-image
</div>
</body>
</html>
A box with a horizontal gradient border transitioning from red to teal appears on the page.
วิธีที่ 2:พื้นหลังและการขยายด้วยองค์ประกอบที่ซ้อนกัน
วิธีการนี้ใช้องค์ประกอบหลักที่มีพื้นหลังไล่ระดับสีและองค์ประกอบลูกที่ซ้อนกันเพื่อสร้างภาพลวงตาของเส้นขอบ
<!DOCTYPE html>
<html>
<head>
<style>
.gradient-parent {
background: linear-gradient(45deg, #ff6b6b, #4ecdc4);
padding: 5px;
display: inline-block;
margin: 20px;
}
.white-child {
background: white;
padding: 20px;
}
</style>
</head>
<body>
<div class="gradient-parent">
<div class="white-child">
Gradient border using background and padding
</div>
</div>
</body>
</html>
A box with a diagonal gradient border (red to teal) created using background and padding appears on the page.
วิธีที่ 3:องค์ประกอบหลอก
ใช้ 22 องค์ประกอบหลอกช่วยให้คุณสามารถเลเยอร์การไล่ระดับสีด้านหลังเนื้อหาหลัก
<!DOCTYPE html>
<html>
<head>
<style>
.pseudo-border-box {
position: relative;
width: 300px;
padding: 20px;
background: white;
margin: 30px auto;
text-align: center;
}
.pseudo-border-box::before {
content: "";
position: absolute;
top: -5px;
left: -5px;
right: -5px;
bottom: -5px;
background: linear-gradient(to bottom, #ff6b6b, #4ecdc4);
z-index: -1;
}
</style>
</head>
<body>
<div class="pseudo-border-box">
Gradient border using pseudo-elements
</div>
</body>
</html>
A box with a vertical gradient border (red to teal) created using pseudo-elements appears on the page.
การเปรียบเทียบ
บทสรุป
เส้นขอบไล่ระดับสีช่วยปรับปรุงการออกแบบ UI ได้อย่างมีประสิทธิภาพโดยใช้วิธีการทั้งสามนี้ เลือก 30 เพื่อความเรียบง่าย พื้นหลัง/ช่องว่างภายในสำหรับการรองรับแบบสากล หรือองค์ประกอบหลอกเพื่อความยืดหยุ่น แต่ละแนวทางมีข้อดีเฉพาะตัวสำหรับการสร้างองค์ประกอบเว็บที่ทันสมัยและน่าดึงดูดสายตา