Today we are doing a very cool project; we are making a list of items and add two buttons.
One button for the list view and a button to switch to grid view.
This project mainly relies on CSS
, but we are using JavaScript
to toggle a class on the main wrapper.
We are going to use CSS
Flexbox
and Grid
to make this work!
Let's get started!
HTML Structure
<div class="container">
<div class="buttons">
<div class="list"><i class="fa fa-list"></i></div>
<div class="grid"><i class="fa fa-th-large"></i></div>
</div>
<div class="wrapper" id="wrapper">
<div class="col">
Column #1
</div>
<div class="col">
Column #2
</div>
<div class="col">
Column #3
</div>
<div class="col">
Column #4
</div>
</div>
</div>
So this is our minimal setup, we have one big container in which we center everything like we learned with flex centering.
We then have a button div which holds the two buttons and then our wrapper which is the actual list.
In the list we have four columns.
.buttons {
display: flex;
}
.buttons div {
margin: 0px 10px;
color: #fffffa;
cursor: pointer;
}
.buttons div > * {
pointer-events: none;
}
.wrapper {
display: grid;
grid-template-columns: 1fr 1fr;
width: 100%;
}
.wrapper.list {
grid-template-columns: 1fr;
}
.wrapper .col {
width: calc(100% - 20px);
height: 200px;
background: #912f40;
display: flex;
justify-content: center;
align-items: center;
color: #fffffa;
margin: 10px;
}
So let's go through these in more depth and explore what's happening.
.buttons {
display: flex;
}
.buttons div {
margin: 0px 10px;
color: #fffffa;
cursor: pointer;
}
.buttons div > * {
pointer-events: none;
}
So our buttons we simply wrap in a flex
container and each div inside we give some margin to space out.
We also add a cursor: pointer
which will make it look like a button.
And then each element inside we set pointer-events: none
so JavaScript
will not fire on the children.
.wrapper {
display: grid;
grid-template-columns: 1fr 1fr;
width: 100%;
}
.wrapper.list {
grid-template-columns: 1fr;
}
For the main part of this project we use our wrapper we tell it to display: grid
and then we define our grid template as: 1fr 1fr
which means it will have two columns.
That's as easy as CSS Grid` is!
Then if it has the .list
class we tell it the template is 1fr
, which is only one column.
Making it switch with JavaScript
So to make this switch, we leverage some pure JavaScript
.
We are adding eventListeners
on our buttons and add or remove the list
class from our wrapper.
Have a look at the result and play on this Codepen:
See the Pen CSS Grid-List view toggle by Chris Bongers (@rebelchris) on CodePen.
Thank you for reading, and let's connect!
Thank you for reading my blog, feel free to subscribe to my email newsletter and connect on Facebook or Twitter
Top comments (0)