This CSS Grid subgrid tutorial demonstrates aligning content within sibling boxes. It addresses the issue of misaligned internal components in horizontally arranged boxes, even when the boxes themselves are correctly sized using Grid.
The solution leverages CSS Grid's subgrid
property. This allows inner grids to inherit the column structure from their parent grid, ensuring consistent alignment.
Step 1: Basic Setup
The HTML uses a parent <article></article>
containing three <section></section>
elements, each with an <h1></h1>
, <ul></ul>
, and <div>. The initial CSS sets the parent as a grid with three equal columns:
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>article {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
}</pre><div class="contentsignin">Copy after login</div></div>
<p><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/173897521347074.jpg" class="lazy" alt="Quick Tip: How to Align Column Rows with CSS Subgrid " /></p>
<p><strong>Step 2: Enabling Subgrid</strong></p>
<p>To utilize <code>subgrid
, each <section>
must also be a grid:
section { display: grid; }
This makes the content within each section fill its respective column.
Step 3: Aligning with Subgrid
The crucial step is setting grid-template-rows: subgrid;
and grid-row: span 3;
within the <section>
CSS:
section { display: grid; grid-template-rows: subgrid; grid-row: span 3; /* or grid-row: 1 / 4 */ gap: 0; /* removes inherited gap */ }
grid-template-rows: subgrid;
makes the inner grid inherit the row structure from the parent. grid-row: span 3;
ensures the inner content spans all rows. gap: 0;
removes any spacing inherited from the parent grid.
Browser Compatibility:
Subgrid support is now excellent across major browsers.
Further Resources:
This improved version provides a more concise and structured explanation, focusing on the key steps and incorporating the images directly within the markdown. The conclusion also links to relevant resources for further learning.
The above is the detailed content of Quick Tip: How to Align Column Rows with CSS Subgrid. For more information, please follow other related articles on the PHP Chinese website!