Table of Contents

About

This page shows you how to arrange horizontally CSS elements.

Display

Block

See CSS Block - Align (Left, Center, Right)

Flex, alignment and justification

See CSS Flex - Align (Left, Right, Center)

.container {
   display: flex;
   justify-content: center;
   align-items: center;
}
.child {
   border: 1px solid aqua;
}
<div class="container">
   <div class="child">Am I ...?</div>
</div>

See also the justify-content article for more values such as left are right

Grid

.container {
   display: grid;
   place-items: center
}
<div class="container">
   <div style="border:1px solid black">Am I ...?</div>
</div>

Absolute / Relative positioning

In case of absolute positioning:

.relative {
    position: absolute;
    left: 50%;
    transform: translate(-50%, 0);
}

where:

  • left:50%: the block starts at 50% left going to the right
  • transform: translate(-50%, 0): then transform with a translate of 50% of the box length to the left

On Bootstrap, this is the class:

  • for the parent: position-relative
  • for the child: position-absolute top-50 start-50 translate-middle

Flex and Auto Margin

With a flex parent, the auto marging value will push the element to:

  • the right for a left auto margin
  • the left for a left auto margin

Demo:

  • The Css
.parent {
  display: flex;
  margin-top: 40px; /* Below the control button of the preview */
}
.child {
  margin-left: auto
}
  • The HTML
<div class="parent">
  <div class="child">
  Child to the right
  </div>
</div>
  • Result: