Explain Codes LogoExplain Codes Logo

Force flex item to span full row width

html
responsive-design
flexbox
css
Alex KataevbyAlex Kataev·Dec 3, 2024
TLDR

To have a flex item spanning the full row, set its flex-basis to 100% and flex-grow to 1. This combination maximizes the item’s width and lets it fully occupy the row:

.full-width-item { flex: 1 0 100%; /* Everyone knows sharing is caring, but this div prefers to take up the whole row. */ }

Enclose it in a flex container with flex-wrap set:

<div style="display: flex; flex-wrap: wrap;"> <div>Item 1</div> <div class="full-width-item">Full Row Item</div> <div>Item 3</div> </div>

Remember, flex: 0 0 100% is ideal for a label or any other element that you want to cover the entire width.

In-depth: flex-wrap and flex item width

The power of flex-wrap

Flex items can jump to new lines when things get crowded, thanks to flex-wrap. It's the humble hero that saves the day when you're dealing with responsive design:

.container { display: flex; flex-wrap: wrap; /* Channeling its inner wrap artist. */ }

Programmatically alter item widths

How about using JavaScript to tweak the flex styles dynamically? Remember, target the container's style properties instead of the label separately.

document.querySelector('.container').style.flexWrap = 'wrap';

The sibling influence

The flex-grow and flex-shrink values of sibling items determine how they share the available space. So handle with care, or your layout might have a sibling rivalry!

Complete guide: flex item and full-width usage

Playing with flex-direction

Play around with flex-direction(row or column) to alter the orientation of your layout. A full-width item behaves differently depending on the direction:

.container-column { display: flex; flex-direction: column; /* The building blocks are vertical now. */ }

The non-existent properties

Contrary to some belief, justify-self: stretch and align-self: stretch are not valid CSS properties. Stick to the rules, folks!

Responsive designs and flexbox

Media queries can adjust flex properties based on screen size, making it a go-to tool for responsive design:

@media (max-width: 600px) { .full-width-item { flex-basis: auto; /* At 600px and below, this div isn't so greedy anymore. */ } }