DEV Community

Cover image for Modern Ways to Center an Element with CSS
Let's Code
Let's Code

Posted on • Edited on

8 3 1

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.

Feel free to bookmark 🔖 even if you don't need this for now. You may need to refresh/review down the road when it is time for you to look for a new role.

CSS translate/transform

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

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

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;
}
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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

If you want a video version:

If you want to support me - Buy Me A Coffee

Image of AssemblyAI

Automatic Speech Recognition with AssemblyAI

Experience near-human accuracy, low-latency performance, and advanced Speech AI capabilities with AssemblyAI's Speech-to-Text API. Sign up today and get $50 in API credit. No credit card required.

Try the API

Top comments (2)

Collapse
 
victorocna profile image
Victor Ocnarescu

Nice one! I did not know the 2-liner code using css grid. Will definitely use this one from now on.

Collapse
 
frontendengineer profile image
Let's Code • Edited

yeah, especially if you have no problem with its current browser support. 👍

i currently use css grid at the moment at work.

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay