While there are various different ways to horizontally align items using CSS, the best way forward is to use the flexbox layout.
In order to use CSS flexbox property efficiently, you have to use elements or tags inside of other elements or tags. The flex property works only if you have elements or tags like div tags inside of other div tags (as parent and child), no matter how deep.
Here’s an example :
<div class="first">
<div class="logo">Header Logo</div>
<div class="links">
<div class="linka"><a href="#">Link A</a></div>
<div class="linka"><a href="#">Link B</a></div>
<div class="linka"><a href="#">Link C</a></div>
</div>
</div>
.first {
display: flex;
/* horizontally aligns child divs */
justify-content: space-between;
align-items: center;
padding-right: 40px;
padding-left: 40px;
background-color: #1f2937;
}
.links {
display: flex;
/* horizontally aligns child divs */
gap: 10px;
font-size: 18px;
}
a {
text-decoration: none;
/* removes underlines from links */
color: #e5e7eb;
}
.logo {
color: #f9faf8;
font-size: 24px;
}
So, what we’ve done is that we’ve simply used something called display: flex property in CSS in the parent div which simply aligns all the child divs under it horizontally in a row.
In the example above, the ‘first’ class has two child divs and the ‘links’ class has three child divs. We’ve used the display: flex property on both these classes to align things horizontally.
This will be the output now :