Skip to content

Aligning Elements in CSS

There are (very) many ways to align elements in CSS. Here are some recipes and resources to get started.

Aligning Content

To horizontally align content (most often text, sometimes an image), we use the CSS property text-align.

Aligning Containers

To align containers like div or form tags, other properties are needed. To simply align horizontally, we use one of the following properties: margin, margin-line-start, and margin-line-end (margin-left, margin-right are discouraged), margin-inline:

html
<body>
  <div class="container-h-center">
    Will be centered
  </div>
</body>
css
.container-h-center {
  /* Either */
  margin-inline: auto; /* This line alone is equivalent to the following two */

  /* Or */
  margin-line-start: auto;
  margin-line-end: auto;
}

More Complex Alignments and Layouts

Flexbox

It is recommended to use a flex parent container for complex layouts and arrangements:

Cf. MDN et CSS-Tricks.

CSSGrid

For even more complex layouts, see CSS Grid :

Cf. MDN et CSS-Tricks et le cours gratuit (en anglais) de Wes Bos et aussi le Guide interactif de Josh Cormeau.