Achieving Nested Grid Alignment with CSS Subgrid
Owner: SnippetBot
Created: 2026-10-23 00:00:41
Size: 2.06 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
.parent-grid {
display: grid;
grid-template-columns: 1fr repeat(2, minmax(100px, 200px)) 1fr; /* Defines 4 columns */
grid-template-rows: auto 1fr auto;
gap: 15px;
width: 90%;
max-width: 1000px;
margin: 20px auto;
background-color: #f9f9f9;
padding: 20px;
border: 1px solid #ddd;
box-shadow: 0 0 10px rgba(0,0,0,0.05);
}
.header, .footer {
grid-column: 1 / -1; /* Span all columns */
text-align: center;
padding: 10px;
background-color: #eee;
border-radius: 5px;
}
.main-content {
grid-column: 2 / 4; /* Occupy the middle two columns of the parent grid */
display: grid;
grid-template-columns: subgrid; /* Inherit column tracks from parent */
grid-template-rows: auto;
gap: 10px;
background-color: #fff;
padding: 15px;
border: 1px solid #ccc;
border-radius: 5px;
}
.main-content h2 {
grid-column: 1 / -1; /* Span across the inherited columns of the subgrid */
margin-top: 0;
color: #333;
text-align: center;
}
.text-section {
grid-column: 2; /* Align precisely with the second column of the parent grid */
background-color: #e6f7ff;
padding: 10px;
border-left: 3px solid #66b3ff;
border-radius: 3px;
}
.image-section {
grid-column: 3; /* Align precisely with the third column of the parent grid */
background-color: #e6ffe6;
padding: 10px;
border-left: 3px solid #66ff66;
border-radius: 3px;
}
/* Example HTML:
<div class="parent-grid">
<div class="header"><h1>Website Header</h1></div>
<div class="main-content">
<h2>Welcome to our site!</h2>
<div class="text-section">
<p>This text is perfectly aligned with the parent grid's second column thanks to subgrid.</p>
<p>It maintains the structural integrity defined by the outer grid.</p>
</div>
<div class="image-section">
<img src="https://via.placeholder.com/150x100" alt="Placeholder Image" style="max-width:100%; height:auto; display:block; margin-bottom: 5px;">
<p>Image aligned with the parent grid's third column, ensuring consistent layout.</p>
</div>
</div>
<div class="footer">Website Footer © 2023</div>
</div>
*/