CSS Block - Align (Left, Center, Right)

About

How to align a visual element with a block display

This is the block part of the horizontal positioning article

You can align visual element on two level:

Level

Box

Box Center

The box will be centered not the content. As a box takes by default 100% of its space, you need to set a width to see the effect.

Css Horizontal Alignement Result

The width of the content is 1110 even if the max-width is 1140 because of the padding because the box sizing is set to border-box

<MATH> 1110 = 1140 - 15 -15 </MATH>

To space the box, the following element were used:

Implementation:

  • Pure Css. It's centering the box not the text. As by default a box has a 100% length, you need to set the length to see the effect.
.center-box {
    margin-left:auto;
    margin-right:auto; /* or margin: 0 auto; */
    width:fit-content;
    border: 1px solid black;
}
<h1 class="center-box">Center</h1>
Bootstrap 4

If you are using bootstrap, you can use the utility class mx-auto.

class="mx-auto" style="width: 200px;"

Box Right

.right-box {
    margin-left:auto;
    width:fit-content;
    border: 1px solid black;
}
<h1 class="right-box">Right</h1>

Text

By default a box takes 100% of its space, you can align the text with the text-align property

h1 {
    text-align: center;
    border: 1px solid black;
}
<h1>Center</h1>





Discover More
How to align horizontally at the center and right position with CSS ?

This page shows you how to arrange horizontally CSS elements. See See justify-content articleleftright In case of absolute positioning: where: left:50%: the block starts at 50% left...



Share this page:
Follow us:
Task Runner