如何用Flexbox/Grid实现无绝对定位的矩形旁堆叠方块布局
Refactoring to Modern CSS (Grid/Flexbox) Without Positioning or Extra Wrappers
Hey there! Let's swap out those old floats and absolute positioning for clean, maintainable CSS Grid—it's perfect for this layout since we don't need extra wrappers around the .square elements. Here's a solution that matches your draft's visual effect while following modern best practices:
Final Code
<div class="container"> <div class="rectangle">Rectangle</div> <div class="square square-1">Square 1</div> <div class="square square-2">Square 2</div> </div>
/* Base styles (cleaned up with box-sizing fix) */ div { border: 1px solid black; padding: 20px; width: 80px; box-sizing: border-box; /* Ensures padding doesn't break your specified width */ } /* Grid container setup */ .container { display: grid; grid-template-columns: auto auto; /* Two columns sized to content */ gap: 10px; /* Uniform spacing between elements (no messy margins!) */ } /* Make rectangle span both rows */ .rectangle { grid-row: 1 / span 2; /* Occupies rows 1 and 2 in the first column */ /* Optional: Uncomment below to match your draft's fixed height */ /* height: 164px; */ } /* Squares auto-position into column 2, rows 1 and 2 */ .square { /* No extra styles needed—Grid handles stacking automatically! */ }
Key Improvements Over Your Draft
- No positioning hacks: We ditch
floatandabsoluteentirely, so layout behavior is predictable and responsive. - No extra wrappers: The
.squareelements stay as direct siblings of the rectangle—no need for nested divs. - Box-sizing fix: Added
box-sizing: border-boxto ensure padding doesn't make elements wider than your specified80px(this was a hidden issue in the original code!). - Clean spacing:
gapreplaces manual margin calculations, making it easy to adjust spacing uniformly. - Flexible height: The rectangle automatically stretches to match the total height of the two stacked squares. If you want a fixed height like your draft, uncomment the
heightline in.rectangle.
Alternative Flexbox Approach
If you prefer Flexbox instead, we can use a small trick to stack the squares without a wrapper—though Grid is more straightforward here:
.container { display: flex; align-items: flex-start; gap: 10px; } .rectangle { /* Match height of two squares to replicate draft */ height: 164px; } .square-1 { margin-bottom: 10px; /* Add spacing between squares */ } .square-2 { align-self: flex-end; /* Pull square 2 down to align with rectangle's bottom */ }
Note: This Flexbox version requires adjusting margins and alignment manually, which is why Grid is the better choice for this specific layout—it's built for 2D (row+column) positioning.
内容的提问来源于stack exchange,提问作者user3108268
相关产品推荐
相关产品推荐

