Explain Codes LogoExplain Codes Logo

How to center-align one flex item and right-align another using Flexbox

html
responsive-design
flexbox
css
Anton ShumikhinbyAnton Shumikhin·Nov 21, 2024
TLDR

For ownership of California-style layout: center-align one flex-item and right-align another by setting justify-content: center on the flex container and applying margin-left: auto to the item destined for the right.

<div style="display: flex; justify-content: center;"> <div>Centered</div> <div style="margin-left: auto;">Right-aligned</div> </div>

This magics the first child into the center and shuttles the second to the right within the flex parent.

Grabbing the reins: Auto margins

Beyond the black and white, painting your layout with auto margins applies granular control over individual flex items and retains responsive balance. Use it for your textual, pictorial, or shiny CTA button children in varying layout scenarios:

  • margin: auto: Centers the item both vertically & horizontally, like a perfect pancake.
  • margin-left: auto: Shoves the item to the right, leaning items just got chic.
  • margin-right: auto: Propels the item to the far left, because the left isn't less.

Here's your recipe. Notice how margin-left: auto; margin-right: auto; ensures centering, not caring for sibling size.

<div style="display: flex; justify-content: flex-start;"> <div>Left-aligned, doesn't get simpler.</div> <div style="margin-left: auto; margin-right: auto;">I ain't moving!</div> <div>Just a right-aligned div.</div> </div>

The Absolute Positioning plot

You got an ace - Absolute positioning. Consider it a weapon - wisely used, it's powerful; otherwise, it's disruptive. It's like proposing with a rose - it's not about the rose, it's about the timing!

<div style="display: flex; position: relative;"> <div style="position: absolute; left: 50%; transform: translateX(-50%);">Centered <!-- The corpse at the feast. --></div> <div>Right-aligned <!-- I swing alone. --></div> </div>

See how the centered div is ghosting the party? Absolute positioning can create overlapping chaos, use with caution.

Using flex-grow to maintain consistency

Consistency is key, isn’t it? The flex-grow property maintains sincere layout harmony even when the couch-mates decide to go rogue on the TV remote:

  • flex-grow: 0; ensures that the item will not grow, maintains its width like a parallel line in geometry.
  • flex-grow: 1; permits the other items to grow, fill space, and enjoy the adventure.

Here’s Practical Pete with the demo:

.centered-item { flex-grow: 0; /* I'm on a diet. */ } .surrounding-items { flex-grow: 1; /* Roomier? Say no more. */ }