How-to: Three Methods for Centering with CSS
Tags: webdev, css, codenewbie, beginners
Published: 2023-08-06 09:17:36

## Introduction

In web development, knowing how to center things with CSS is an essential skills. Like many things in the programming world there is more than one way to do it. Some ways are better than others, but there’s not always a best way. It often depends on the context of the situation. 

In this blog post, I’ll share my three favorite ways for centering elements using CSS. I first learned about these methods from [Kevin Powell’s ‘Conquering Responsive Layouts’ course](https://courses.kevinpowell.co/conquering-responsive-layouts) (and in fact, wrote a short [blog post in December 2022](https://ananfito.hashnode.dev/responsive-web-design-with-3-lines-of-css) about it, but only covered the first method in that post). Here, I’d like to discuss all three methods: `margin` and `max-width`, `flex`, and `grid`. 

I’ll be assuming you have some familiarity with CSS, flex, and grid. Also, for demonstration purposes I’ll be using the example of a blog website with a single-column layout. I will provide snippets of code throughout the post, but if you’d like to see the source code and live example for these methods, you can view [the repo here](https://github.com/ananfito/LearnInPublic/tree/main/center-with-css) and the [live site here](https://ananfito.dev/LearnInPublic/center-with-css).

## Method 1: Using `margin` and `max-width`

This is probably my favorite way to center elements in CSS. I like it because it’s quick and simple. However, because of its simple approach this also means it’s best used in simple situations. This method works best when you want to center something directly in a vertical column. More complex layouts will require a different or combination of techniques. 

If you want to center the `body` (or any element within its parent container), a quick and easy way to do that is with `margin` and `max-width`:

```css
/* METHOD 1: Using margin and max-width */
    .blog-post {
      margin: 0 auto;
      max-width: 600px;
    }
```

In the `margin` property, the first value sets the top and bottom margin are set to `0` so that they touch whatever is above and below them. In other words, there’s no gap between the elements but if you wanted to have some space you could set the first value to something other than `0`.

The second value, `auto`, will automatically set the left and right margin to the same amount with whatever space is available. This ensures that the element is centered along the vertical axis of the page. 

Then the `max-width` property ensures that the width of the element does not extend beyond the numerical value. In this case, the maximum width will be `600px` but it can be set to whatever value is desired/needed. 

It’s not used in this example, but you can also add `width: 80%` (or whatever percentage you desire) so that the element fills 80% of the available width. This will allow for a little bit of space on the left and right. This is ideal on mobile or tablet devices where you might want a little bit of space between the left and right edges of the content and the edge of the screen. 

**NOTE**: When `max-width` is used in conjunction with `width: 80%` the element will fill 80% of the available width up to the maximum width. 

If you’d like to see a demonstration of this in action, you can view a [live example](https://ananfito.dev/LearnInPublic/center-with-css/method1.html) and the [source code](https://github.com/ananfito/LearnInPublic/blob/main/center-with-css/method1.html).

## Method 2: Using `flex`

Another common method for centering elements is to use `flex` with `justify-content` and `align-items`. Continuing with the same example let’s look at how we would use this to center items within a single-vertical column: 

```css
/* Method 2: Using flex */
.blog-post-container {
  display: flex;
  flex-direction: column; /* REMINDER: with `column`, the main axis is horizonal and cross axis is vertical */
	align-items: center; /* `align-items` still affects the cross axis, but with column it works vertically */
}
```

Here we’ve set the `.blog-post-container` class to have a display of `flex` and centered its children elements using `align-items`. Since the `flex-direction` is set to column the `align-items` affects the cross axis which the vertical axis. This is what places the elements within the center of the flex container. 

If you’d like to see a demonstration of this in action, you can view a [live example](https://ananfito.dev/LearnInPublic/center-with-css/method2.html) and the [source code](https://github.com/ananfito/LearnInPublic/blob/main/center-with-css/method2.html).

## Method 3: Using `grid`

Lastly, we can use `grid` to center things too. Using our same blog website example, let’s look at how we would do this: 

```css
/* Method 3: Using grid */
.blog-post-container {
	 display: grid;
 }
.blog-post {
  justify-self: center; /* this places the div in the center of the grid-column */
	max-width: 600px; /* this prevents the div from filling the entire space */
}
```

Here we have a little bit of a different set up. We have to set the container (in this case `.blog-post-container`) to use `grid` while at the same time setting the properties for the blog post itself. 

Since we’re only working with a single column layout we don’t need to worry about `grid-template-columns` or `grid-template-rows` or `grid-template-areas`. Instead, we can focus our  attention on the `.blog-post` class. 

In this above snippet, we can use the `justify-self` property to center this class within the `grid` container. And just like with Method 1 we want to set the `max-width` property so that the content doesn’t span the entire width of the column or window. 

If you’d like to see a demonstration of this in action, you can view a [live example](https://ananfito.dev/LearnInPublic/center-with-css/method3.html) and the [source code](https://github.com/ananfito/LearnInPublic/blob/main/center-with-css/method3.html).

## Conclusion

Those are my three favorite techniques for centering elements. These work best within a single-column layout, but can also be used within more complex layouts (if you want to center something within a section). 

I mostly lean toward using Method 1, but what’s great about all of these is they don’t take up more than a few lines of code. This makes them great in a pinch when you want to center something quickly without worrying too much about the layout. 

If you’re looking to learn more about these techniques and other ways of designing responsive web design, check out the resources listed below. Note, these are **_NOT_** affiliate links. These are just the resources I found useful in learning about these concepts. You can also check out the References section for the documentation I referenced in writing this post. Happy coding!

## Resources

- [CSS Flexbox Tutorial with Flexbox Properties Cheat Sheet](https://www.freecodecamp.org/news/css-flexbox-tutorial-with-cheatsheet/) (freeCodeCamp) - In-depth tutorial on how to use CSS flex including `flex-direction`, `justify-content`, `align-content`, `align-items`, `align-self`, and more. Plus, there’s a video tutorial linked in the post.
- [Complete CSS Grid Tutorial with Cheat Sheet](https://www.freecodecamp.org/news/css-grid-tutorial-with-cheatsheet) (freeCodeCamp) - In-depth tutorial on how to use CSS grid including `grid-template-columns`, `grid-template-rows`, `grid-template-areas`, and more. Plus, there’s a video tutorial linked in the post.
- [Kevin Powell’s ‘Conquering Responsive Layouts’ course](https://courses.kevinpowell.co/conquering-responsive-layouts) - Free 21-day course which gradually guides you through designing mobile-first websites using `flexbox` and other great tools
- [Scrimba’s Learn CSS Grid](https://scrimba.com/learn/cssgrid) - Free interactive tutorial spread out over 18 tutorials building a website, an image grid, and an article. Plus, you’ll learn how to combine CSS grid with flexbox.

## References

- [Aligning Items in a Flex Container](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_flexible_box_layout/Aligning_items_in_a_flex_container) (MDN Docs)
- [CSS grid layout](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_grid_layout) (MDN Docs)
- [CSS Grid Module](https://www.w3schools.com/css/css_grid.asp) (w3schools)

## Thanks for reading

Thanks for reading. I hope you found it useful. **What are you favorite techniques for centering content with CSS?** Let me know in the comments. Hearing your thoughts makes this more of a conversation and helps us both learn. 🚀