Skip to content

Template Grid

Use nested template-for bindings to create a grid.

Grid Example:

Code

The following example assumes that you have imported the component and set up the theme.

Grid
<sv-template id="grid">
<!-- Template markup -->
<template>
<div
class="grid"
style="grid-template: repeat([[rows]], 1fr) / repeat([[columns]], 1fr)"
aria-label="Shows a grid [[ rows ]] by [[ columns ]] cells."
>
<!-- repeat rows and save the index in rowIndex -->
<div class="row" template-for="rowIndex of rows">
<!-- repeat columns on each row and save the index in columnIndex -->
<div class="cell [[ rowIndex % 2 == columnIndex % 2 ? 'light' : 'dark' ]]" template-for="columnIndex of columns"></div>
</div>
</div>
</template>
<!-- Scoped style -->
25 collapsed lines
<style>
.grid {
display: grid;
max-inline-size: 400px;
aspect-ratio: 1;
margin: auto;
border: var(--sv-bdr-sz-lg) solid var(--sv-gray-5);
border-radius: var(--sv-bdr-rad-sm);
}
.row {
display: contents;
}
.cell {
&.light {
background-color: var(--sv-gray-5);
}
&.dark {
background-color: var(--sv-gray-6);
}
}
</style>
</sv-template>
<h3>Grid Example:</h3>
<div class="grid-container">
<!-- Render and use the template -->
<sv-template prop-columns:js="8" prop-rows:js="8" use="grid"></sv-template>
</div>