如何用纯CSS为Div实现平行正方形背景图案(非图片)
Solution for Aligned 3px Square Background Pattern (Pure CSS)
Hey Jorge, I totally get what you're looking for—those perfectly aligned 3px square patterns (no staggered checkerboard here) for your div's background, using only CSS without any image assets. I’ve been in that "searching for hours" spot too, so here’s a solid solution that fits your needs:
Code Implementation
.square-grid-bg { /* Adjust width/height to match your div's requirements */ width: 100%; height: 300px; /* Base background color (the space between squares) */ background-color: #ffffff; /* Create the square grid with two repeating linear gradients */ background-image: /* Horizontal lines to form square tops/bottoms */ repeating-linear-gradient(to bottom, #000000 0px, #000000 3px, transparent 3px, transparent 6px), /* Vertical lines to form square left/right sides */ repeating-linear-gradient(to right, #000000 0px, #000000 3px, transparent 3px, transparent 6px); }
How It Works
- We stack two
repeating-linear-gradientlayers: one for horizontal lines and one for vertical lines. When combined, they form perfectly aligned 3px squares (no staggered checkerboard shift). - The
6pxvalue defines the full cycle (3px square + 3px gap between squares). If you want squares to sit directly next to each other with no gap, just change thetransparent 6pxtotransparent 3px(this will make squares fill the entire background without spacing). - Swap out
#000000for your desired square color, and#fffffffor your preferred background gap color. - This approach uses 100% CSS, no image files, and creates a uniformly repeating grid exactly as you asked for.
Alternative Simplified Version
If you prefer a more concise syntax, this achieves the exact same result:
.square-grid-bg { width: 100%; height: 300px; background-color: #ffffff; background-image: linear-gradient(#000000 3px, transparent 3px), linear-gradient(90deg, #000000 3px, transparent 3px); background-size: 6px 6px; background-repeat: repeat; }
内容的提问来源于stack exchange,提问作者Jorge
相关产品推荐
相关产品推荐

