I mainly use two methods for centering elements, one is the right way while the other one is a hack. Here are the two methods:
Sample markup:
<div class="wrap">
<div class="element"></div>
</div>
1. Using Flexbox
Here is how you can center elements using flexbox:
.wrap {
display: flex;
justify-content: center;
align-items: center;
}
It's just 3 lines of code and I don't think it can get any easier than this. codepen
2. Using Position
.wrap { /* nothing here */}
.element {
position: relative;
top: 50%;
left: 50%;
transform: translateX(-50%) translateY(-50%);
width: 156px;
}
This is a "hacky" way, you'd always have to give some width to your child element and make some adjustments here and there... codepen
Frontend Engineer | Hashnode Alumnus