This is my 10th write up on dev.to site. Example of CSS grid based on variable. Full source code is included as a flems.io link.
CSS grid
CSS grid is one of technics for UI definition (you may know CSS Flexbox too).
Using CSS grid one can define visual template for content displayed on web page.
As frontend developers we can use "static template" with no changes. Sometimes, there is a good practice to change layout based on condition defined with Media Queries.
Did you know we can change our template via variable's value? Let's do this.
CSS grid layout example
Assume we need place four buttons inside div and want change their positions.
HTML code:
<div class="grid-area ">
<button class="btn-1 bg-blue" > A </button>
<button class="btn-2 bg-blue" > B </button>
<button class="btn-3 bg-blue" > C </button>
<button class="btn-4 bg-blue" > D </button>
</div>
CSS code:
.grid-area {
display: grid;
gap: 1rem;
}
This example shows fixed layout, there is nothing we can change. Let's do the magic.
Since we use VueJS, define variable holding class name we add to the div (grid countainer) and some CSS classes with different layout for our four buttons.
...
data: function(){
return {
template: "",
}
},
...
Example definitions of different CSS grid templates:
.grid-area-4 {
grid-template-areas: "area1 area2 area3 area4"
}
.grid-area-2-2 {
grid-template-areas: "area1 area2"
"area3 area4"
}
.grid-area-1-2-1 {
grid-template-areas: "area1 area1"
"area2 area3"
"area4 area4"
}
.grid-area-2-1-1 {
grid-template-areas: "area1 area2"
"area3 area3"
"area4 area4"
}
.grid-area-1-1-2 {
grid-template-areas: "area1 area1"
"area2 area2"
"area3 area4"
}
Each button has its own class .btn-1, .btn-2 etc.
.btn-1 {
grid-area: area1;
}
.btn-2 {
grid-area: area2;
}
.btn-3 {
grid-area: area3;
}
.btn-4 {
grid-area: area4;
}
A small change of HTML code is enough to do the magic:
<div class="grid-area " :class="template">
<button class="btn-1 bg-blue" > A </button>
<button class="btn-2 bg-blue" > B </button>
<button class="btn-3 bg-blue" > C </button>
<button class="btn-4 bg-blue" > D </button>
</div>
Using VueJS variable template we can define dynamic class and apply it to the div (grid container).
I suppose my explanation is clear, here you can see full source code and playground on flems.io
Hope this help you :-)
Top comments (0)