可以通过CSS的linear-gradient
背景渐变技术,在单个DIV元素上实现角部填充颜色的效果。以下是几种实现方式:
.corner-colored {
width: 200px;
height: 200px;
background:
linear-gradient(45deg, #f00 10px, transparent 0) top left,
linear-gradient(-45deg, #0f0 10px, transparent 0) top right,
linear-gradient(135deg, #00f 10px, transparent 0) bottom left,
linear-gradient(-135deg, #ff0 10px, transparent 0) bottom right;
background-size: 50% 50%;
background-repeat: no-repeat;
}
虽然题目要求只用一个DIV,但使用伪元素也是常见做法:
.corner-colored {
position: relative;
width: 200px;
height: 200px;
}
.corner-colored::before {
content: "";
position: absolute;
top: 0;
left: 0;
width: 20px;
height: 20px;
background: #f00;
}
.corner-colored::after {
content: "";
position: absolute;
top: 0;
right: 0;
width: 20px;
height: 20px;
background: #0f0;
}
.corner-colored {
width: 200px;
height: 200px;
border-top: 20px solid #f00;
border-right: 20px solid #0f0;
border-bottom: 20px solid #00f;
border-left: 20px solid #ff0;
box-sizing: border-box;
clip-path: polygon(
0 20px, 20px 20px, 20px 0, calc(100% - 20px) 0,
100% 20px, 100% calc(100% - 20px), calc(100% - 20px) 100%,
20px 100%, 0 calc(100% - 20px)
);
}
.corner-colored {
width: 200px;
height: 200px;
background:
/* 左上角 */
linear-gradient(to bottom right,
transparent 0%, transparent 70%,
#f00 70%, #f00 100%) top left,
/* 右上角 */
linear-gradient(to bottom left,
transparent 0%, transparent 70%,
#0f0 70%, #0f0 100%) top right,
/* 右下角 */
linear-gradient(to top left,
transparent 0%, transparent 70%,
#00f 70%, #00f 100%) bottom right,
/* 左下角 */
linear-gradient(to top right,
transparent 0%, transparent 70%,
#ff0 70%, #ff0 100%) bottom left;
background-size: 50% 50%;
background-repeat: no-repeat;
}
这些方法都可以在不使用额外HTML元素的情况下,仅通过CSS实现角部填充颜色的效果。你可以根据需要调整颜色、大小和角度。