Tuesday Tips | The Modern Way to Center Content in CSS
Manage episode 313190380 series 3261464
Today is December 8, 2020, and for this Tuesday Tips episode we're covering The Modern Way to Center Content in CSS
Let's dive in!
----
For many years the bane of any web designer's existence was something simple: centering an object on the page. Horizontally centering was one thing, but getting an item to vertically center was a whole different monster. Even worse was both vertically and horizontally centering an element. However, modern CSS stylings have made this a snap with just a few lines of code. Gone are the days of absolute positioning an element 50% of the top and left of its container and bumping it back negative 50% with a transform. Now we can use Flexbox or CSS Grid to quickly center the element and move on.
----
Flexbox makes it very easy to align items in the center of the container with just three lines of CSS. Just set the display to flex
and center the items horizontally (justify-content: center
) and vertically (align-items: center
).
.container {
display: flex;
justify-content: center;
align-items: center;
}
Now all items originate from the center of the container!
It is important to note that if you change to flex-direction: column
the properties have the opposite effect: justify-content
becomes the vertical axis and align-items
becomes the horizontal. Think of it as rotating the container element's axes.
----
Meanwhile, CSS Grid makes it even easier by only needing place-items: center
to center elements in the grid. Just set the display to grid
, place the items, and you're off to the races.
.container {
display: grid;
place-items: center;
}
If you want to control the individual axes you can use the same properties as we did with Flexbox instead, justify-content
for the horizontal axis and align-items
for the vertical.
.container {
display: grid;
justify-content: center;
align-items: center;
}
Never get tripped up with centering an element on your website again. Whether you are using Flexbox or CSS Grid add a couple lines of code and move on to something more deserving of your skill and attention.
----
Today’s Tuesday Tips was adapted from a series of posts on Daily Dev Tips.
----
Want to know more? Head to fewdaily.com for more of today’s topics and other front-end web content! If you liked what you heard be sure to rate, review, and subscribe on your platform of choice. That's all for today, tune in tomorrow!
37 에피소드