Explain few methods to center elements in webpages?
Centering using Flexbox
Let's say we want to center a div within its parent container, both horizontally and vertically.
For a long time, this was a notoriously tricky challenge, especially if we wanted to keep the element in-flow.
When Flexbox launched, this challenge became a lot less daunting; we could do it in 3 lines of CSS:
Centering using Grid
In CSS Grid, we can use the same trick. For consistency, we'll use align-content
instead of align-items
(though both should produce a similar result in this circumstance).
Because we're setting justify-content
and align-content
to the same value, we can take advantage of a shorthand:
The place-content
property will set both justify-content
and `align-content at the same time. This means that we now have a CSS centering trick that's just 2 declarations long!
Modern CSS is pretty cool.