CSS Grid for the Fearsome Beginner
I am learning how to use CSS grid, and I’m having a lot of fun with it. I have almost no experience with CSS. I was very intimidated before I knew anything about it, but as soon as I did just a couple of minutes of research, I saw that it is very easy to apply. The fear went away, and I started having fun!
Here, I will list and explain some quick and simple CSS grid basics and keywords as I use them, and I will continue to update this post as I learn.
I’m starting with this simple HTML:
I have a body, a div with the class container,
and 4 divs inside the container with a little text. This HTML alone looks like this on my web page:
Step 1: background-color
and display: grid
Time to make a grid!
I write a different block for each element. To refer to a tag, I just type the tag name. For a class name, precede it with a period. I’m keeping the body element as my background and making a grid of the container div. To see the difference, I’m assigning all of my elements background colors.
Then, in the container block, I write one little line of code to create my grid. display: grid
.
Here’s what we get, so far:
It doesn’t look like it yet, but this IS a grid!
Step 2: Make it look like a grid with Columns, Rows, Gap, Margin
Now, I’ll make it apparent that we do have a grid here by creating columns, rows, a gap and a margin.
I’ll add this into the container block:
grid-template-columns: 1fr 1fr;
grid-template-rows: 1fr 1fr;
grid-gap: 5px;
A column or row value can be a length, percentage or fraction. I like fraction. It’s so simple. I want two columns and two rows, so I create a fraction for each, with 1fr
.
A grid gap is easy to make with a pixel value; 5px
in this case.
And now I have:
Now this is very clearly a grid!
Now, to make my blue “container” really look like a container, it would be nice to have some margins around my four divs.
In the div block, I’ll add margin: 3px
.
Wow, what a grid! Thanks to only this bit off CSS:
Playing with css like this a lot of fun, because I don’t risk my program. I’m not going to break my code by going wild in the css file! It’s actually a great break from debugging.
I will add more CSS fun here as I go. I’d love for you to share your experience and suggestions in the comments!
Resources: