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/tr…


This content originally appeared on DEV Community and was authored by Let's Code

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 for 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

If you want a video version:


This content originally appeared on DEV Community and was authored by Let's Code


Print Share Comment Cite Upload Translate Updates
APA

Let's Code | Sciencx (2021-08-23T20:39:17+00:00) Modern Ways to Center an Element with CSS. Retrieved from https://www.scien.cx/2021/08/23/modern-ways-to-center-an-element-with-css/

MLA
" » Modern Ways to Center an Element with CSS." Let's Code | Sciencx - Monday August 23, 2021, https://www.scien.cx/2021/08/23/modern-ways-to-center-an-element-with-css/
HARVARD
Let's Code | Sciencx Monday August 23, 2021 » Modern Ways to Center an Element with CSS., viewed ,<https://www.scien.cx/2021/08/23/modern-ways-to-center-an-element-with-css/>
VANCOUVER
Let's Code | Sciencx - » Modern Ways to Center an Element with CSS. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/08/23/modern-ways-to-center-an-element-with-css/
CHICAGO
" » Modern Ways to Center an Element with CSS." Let's Code | Sciencx - Accessed . https://www.scien.cx/2021/08/23/modern-ways-to-center-an-element-with-css/
IEEE
" » Modern Ways to Center an Element with CSS." Let's Code | Sciencx [Online]. Available: https://www.scien.cx/2021/08/23/modern-ways-to-center-an-element-with-css/. [Accessed: ]
rf:citation
» Modern Ways to Center an Element with CSS | Let's Code | Sciencx | https://www.scien.cx/2021/08/23/modern-ways-to-center-an-element-with-css/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.