Danjel.dev 🏋️

Centering with CSS

The margin version.

.margin {
  max-width: 60ch; 
  margin: 0 auto;
}

Using max-width as opposed to a static width with media queries really helps to make the site responsive. It saves a lot of lines of CSS to adjust for every viewport. It's only 4 lines of CSS for a responsive box which could contain anything, text, a header, a footer or anything basically.

The flexbox version

.container {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.centered {
  background-color: lightgray;
  max-width: 60ch;
}

The grid version

Because it doesn't have the width "problem" as with margin and flexbox, this is my favorite. Native not supported in Internet Explorer 11.

.container {
  display: grid;
  grid-template-columns: 1fr minmax(auto, 600px) 1fr;
}

.centered {
  background-color: lightgray;
  grid-column: 2/3;
}