Create a self-centering, full-width stripe with CSS Grid
In this lesson, we'll take simple HTML and create a stripe with a full-width background color and centered content. We'll do all of this without adding an additional "wrapper" level in our HTML by using CSS Grid.
Duration
2 min
Access
Free
Transcript
Available
In this lesson, we'll take simple HTML and create a stripe with a full-width background color and centered content. We'll do all of this without adding an additional "wrapper" level in our HTML by using CSS Grid.
Video Transcript
Bryan Robinson: We'll start with some HTML. There's a section with a class of stripe and some number of HTML elements as direct children of that stripe. In this case, we have an <h1> and a <p> tag. We'll move down to our CSS, and we'll begin by setting the display property to grid.
You can see that a couple of small things have changed. In a grid context, margins no longer collapse, and that was accounting for the additional white space added to the stripe.
Next, we need to set our grids columns, and we'll use the CSS property grid-template-columns to do that. Normally, we would set multiple columns for a grid, but in this case, we only want one column, and we're going to use the minmax() function in CSS to accommodate various seizes.
We're going to have it automatically sized down to whatever size that content needs with the key word auto, and then we'll use 900px to set a max width on this area.
As we stretch this out, our content stays anchored at 900px mark, but we want to be able to be centered automatically in our grid. To do that we use the box alignment property justify-content and we'll allow it to be centered in our area.
As we size it out, it automatically will center itself. This allows for you to add no additional markup to your template but have a nice centered area for your content.
You'll notice that when we size it all the way down, that we're lacking a little bit of space on the left- and right-hand side. We can fix this with a little bit of padding on the left and right. I like to add a little bit of top and bottom padding as well to keep things consistent.
Now at a mobile size we have a nice comfortable margin on the outsides, and on the full-width desktop size we have a nice 900px centered column.