In this article, we’ll look at four ways to horizontally and vertically center a div using CSS Grid. Of course, these centering techniques can be used on any kind of element. We’ve previously covered how to center elements horizontally and vertically using Flexbox and positioning with transforms. Setting UpLet’s first create a container with a simple box element inside it that we’ll use to demonstrate these centering methods. Here’s the HTML:
And here’s our starting CSS:
In all our examples, we’ll be using the Now, let’s look at the various ways to center our div. 1. Center a Div with CSS Grid and place-selfMy favorite way to center an element with Grid is to use the Centering our div is as simple as this:
See the Pen The Using An advantage of using 2. Center a Div with CSS Grid, justify-content and align-itemsLet’s now look at what’s involved with using Grid with The Just like the Let’s return to our test HTML and add the following code to the parent container:
See the Pen An apparent advantage of this method is that it involves less code, as the centering is handled by the container. But in some ways it’s also a disadvantage to target the div via its container, as any other element in the container will also be affected. 3. Center a Div with CSS Grid and Auto MarginsAs always, we’ll target the parent container with
See the Pen (As an aside, there are lots of other cool things you can do with CSS margins.) 4. Center a Div with CSS Grid and place-itemsThe
See the Pen Like the In contrast to ConclusionEach of these methods lets you center a div horizontally and vertically within a container. As I said, my preference is the the In the demo examples, we’ve just used an empty div, but of course you can add content to the div and the centering will still work. And, once again, these centering techniques work on elements other than divs. Further reading: via Pixel Lyft https://ift.tt/Q7EJUq6
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. Archives
April 2023
Categories |