CSS - Horizontal Layout (Center)
Table of Contents
About
How to arrange horizontally css element
Articles Related
Display
Block
Flex
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