Centering Content with CSS

Absolutely no shade to people who still use:
 <center>My centered text!</center>


I do it occasionally because it's so freaking simple. But there are some better ways!

<div class="myCenteredDiv">Look, I'm centered!</div>
.myCenteredDiv {
  margin:0 auto;
  width:300px;
  background-color:limegreen;
  padding:10px;
  }

Example:
Look, I'm centered!


The important part is the margin and width properties. This only works if your div has a width. The width of the item determines how it's centered.

Another way is using flexbox which has been a godsend for getting stuff to do what I want it to do:
<div class="flex-wrapper">
  <div class="myCenteredDiv">Look, I'm centered!</div>
</div>
.myCenteredDiv {
  background-color:limegreen;
  text-align:center;
  padding:10px;
  width:300px;
}
.flex-wrapper {
  display:flex;
  justify-content:center;
}

Example:
Look, I'm centered!


Please note that the width is not required for this one. If you do not set a width, it will only be as wide as the div itself.

If you want to center the text inside the div, but not necessarily the div itself, you could do this:
<div class="myCenteredText">
  <p>My text is centered!</p>
</div>
.myCenteredText {
  text-align:center;
}

Example:

My text is centered!



The 'text-align' value affects all inline or inline-block elements in the container. Here is a list of all inline elements. Images are included, so you can use this to center an image simply.
<div class="myCenteredImage">
  <img src="https://sadgrl.online/images/new/logo.gif">
</div>
.myCenteredImage {
  text-align:center;
}

Example:


Note you must apply the text-align value to a parent of the centered item (like a div). If you applied it to just the image, it wouldn't work.

Hopefully this helps you center items on your website!