This site is mobile accessible. Press the "Tap Here" button to use a smaller font-size.

Smartphone icons created by Freepik - Flaticon

6.7 CSS Align

Center Align Elements

To horizontally center a block element (like <div>), use margin: auto; Setting the width of the element will prevent it from stretching out to the edges of its container. The element will then take up the specified width, and the remaining space will be split equally between the two margins:

This div element is centered.
Example 1: centering an element
.center {
  margin: auto;
  width: 50%;
  border: 3px solid green;
  padding: 10px;
}

Note: Center aligning has no effect if the width property is not set (or set to 100%).

Center Align Text

To just center the text inside an element, use text-align: center;

This text is centered.
Example 2: centering text inside an element
.center {
  text-align: center;
  border: 3px solid green;
}

Tip: For more examples on how to align text, see the CSS Text Effects chapter.

Center an Image

To center an image, set left and right margin to auto and make it into a block element:

Example 3: center align an image
img {
  display: block;
  margin-left: auto;
  margin-right: auto;
  width: 40%;
}