Modern Ways to Center an Element with CS ...

Modern Ways to Center an Element with CSS

Sep 04, 2021

Here are some Modern Ways to Center an Element with CSS

CSS has come a long way on how to center 🎯 an html element. I can still remember some ways using tables and floats. Not pretty but it works during that time. 😃😎 Fast-forward, it is easy and can be done with few lines of code.

CSS translate/transform

// maybe best to support old browser
.container {
    position: relative;
}

.child {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

CSS flexbox (3-liner code)

https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Flexbox

// most popular because of current browser support
.container {
  display: flex;
  justify-content: center;
  align-items: center;
}

CSS grid (2-liner code)

https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Grids

// the future
.container {
  display: grid;
  place-items: center;
}

In case you want to play and see this code in action:
Codepen: https://codepen.io/angelo_jin/pen/qBmwyzr

Here is a youtube video if you like a video format.

https://youtu.be/wzOSTkKeo2c

Gefällt dir dieser Beitrag?

Kaufe letscode77 einen Kaffee

More from letscode77