Explain Codes LogoExplain Codes Logo

Center One and Right/Left Align Other Flexbox Element

web-development
responsive-design
best-practices
layout
Nikita BarsukovbyNikita Barsukov·Jan 4, 2025
TLDR

To get our desired layout, we'll have the container set as a flex box and take advantage of margin auto:

<div style="display: flex; justify-content: center;"> <div>Aye sir! I'm in the middle!</div> <div style="margin-left: auto;">I'm enjoying the scenic right!</div> </div>

Voilà! The first div is centered and the second one is right-aligned. Mind-blowing margin sorcery, right? Now, let's dive deeper.

Less Known Flexbox Techniques

Welcome to the vault of flexbox techniques, let's see a few more tricks.

Optical Illusion with Invisibility Cloak

Ever thought of using a twin to balance the sacred alignment while keeping it invisible? Your wish is my command!

<!-- Harry Potter and the Order of the Flex Items --> <div style="display: flex; justify-content: center;"> <div style="visibility: hidden;">Hey! Where did I go?</div> <!-- The Invisible Twin --> <div>I'm sitting right in the middle!</div> <div>I'm "right", always!</div> </div>

Positioning Like a Pro

If you want to practice some pro-level positioning magic, you can try position: absolute along with position: relative on the container... like this:

<!-- Fast & Furious: Absolute Drift --> <div style="position: relative; display: flex; justify-content: center;"> <div>Chilling in the middle!</div> <div style="position: absolute; right: 0;">Living life in the fast lane! (right lane, to be precise)</div> </div>

Growth Mindset

Flex items can grow to fill extra space within their container. It's all about having the right flex-grow mindset.

<!-- The Incredible Flex Hulk --> <div style="display: flex;"> <div style="flex: 1; text-align: center;">I'm taking all the room I can get!</div> <div>I'm just here for the ride.</div> </div>

Advanced Alignment Techniques in Flexbox

The symphony of positioning doesn't stop at basic flex properties. Let’s delve deeper:

Spacing and Overflow

Watch your spacing! Overflowing items won't stick to the script and will mess up your alignment.

Transform Magic

Craving some more magic? Use transform: translateX(-50%) to shift elements without disrupting the layout flow.

Agility in Adaptation

Flexboxes are wonderful, but not all screen sizes are. Make sure you test your layout to ensure it doesn't fail on different devices.

Juggling Multiple Items

Working with more than two items? Balance them with justify-content: space-between or space-around and individualize them with align-self.