Align two inline-blocks left and right on same line
For a quick solution to align two inline-blocks left and right on the same line, the CSS property float
is your friend. Here are the basics:
No hocus-pocus needed, just float the latter element to the right. They will align perfectly like two peas in a pod on the same line.
Flexbox: A modern toolkit for alignment
Flexbox offers a cleaner and more flexible solution. Instead of fighting with floats and clears, aligning elements becomes a breeze.
Here, justify-content: space-between;
works as a peace negotiator, ensuring that the elements maintain their personal space.
Grid layout: The control freak's dream
But wait! Can we afford more control? Yes, with CSS Grid Layout!
CSS Grid takes alignment to the next level. Got a complaint? Grid has you covered.
Whitespace Begone! Embrace zero font size
One of the curveballs inline-block
throws at you is the dreaded whitespace.
font-size: 0
is the secret sauce to eliminate whitespace. Never again will your elements get "spacing anxiety".
Backup plan: text-align
Worried about your grandma still using IE7/9? Apply a touch of text-align
and witness its magic!
Text-align: the fair godmother of Flexbox for older browsers.
Keeping things responsive with Bootstrap
Bootstrap 4: classier alignment solutions for the lazy coder.
Who said good old Bootstrap isn't cool? Just slap on the correct classes and call it a day!
Floats and absolute positioning: thanks, but no thanks
While floating and absolute positioning can do the trick, the modern CSS warriors greatly discourage this approach. Your future self will thank you.
JavaScript: For real-time alignment
To serve content that is not only pleasing to the human eye but also to handle window size changes
, use some JavaScript magic.
JavaScript adjusting text-align
is like a DJ mixing the tracks based on the groove of the crowd (here, screen size).
Dealing with inline-block oddities
Inline-block
elements can sometimes act out. A dose of vertical-align: middle
will keep the misalignment at bay.
Was this article helpful?