CSS Block - Align (Left, Center, Right)
Table of Contents
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:
- on the text level: the text in the box is aligned
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.
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:
- CSS - Padding to set the gutter
- margin auto to center the box horizontally
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>