Explain Codes LogoExplain Codes Logo

Style input element to fill remaining width of its container

html
responsive-design
css
flexbox
Nikita BarsukovbyNikita Barsukov·Nov 13, 2024
TLDR

To have an input element take up the remaining space in a container, use a flexbox layout. Assign display: flex; to the parent and flex: 1; to the input for it to automatically envelop the leftover:

.cozy-container { display: flex; // Makes the box flex its muscles } .expandable-input { flex: 1; // Make like Elsa and "let it grow" }
<div class="cozy-container"> <label>The usual suspect:</label> <input type="text" class="expandable-input"> </div>

This delivers a supple input that adjusts to the available elbow room.

Capable on older browsers

While flexbox leads the pack in modern layouts, older browsers might crave a fallback worth their vintage. The label and input can play table-cells in a setting styled with display: table;:

.old-school-container { display: table; width: 100%; // Full throttle } .cell-label, .cell-input { display: table-cell; // Cells at work } .cell-input { width: 100%; // All in or nothing }
<div class="old-school-container"> <label class="cell-label">Ancient Label:</label> <input type="text" class="cell-input"> </div>

This approach ensures a dynamically adjusting input, keeping in step with label size changes.

Dealing with a crowd

When trying to manage multiple elements such as buttons online with an input, flex properties can be manipulated to distribute vacant space:

.multi-talented-container { display: flex; } .flexin-item { // Tweak the flex 'grow' factor to taste flex: 0.5; // Takes half the available space like a considerate sibling flex: 1; // Takes all the remaining space like an only child flex: 2; // Takes twice the space of siblings with 'flex: 1', the family favourite }

Keeping things neat

In a flexbox layout, keeping elements from spilling onto a new line is paramount. The flex-wrap property is your ally:

.tight-lid-container { display: flex; flex-wrap: nowrap; // Keep the wrapping paper for gifts }

Handling growth spurts

So the label's width suddenly grows overnight? No worries! A flexbox layout ensures your input sideline's its drama and adjusts its size to match.

Popularity contest

Never forget to check browser compatibility for flexbox. Remember to use vendor prefixes when needed:

.popular-kid-container { display: -webkit-flex; /* Old versions of Safari, the hipsters' favourite*/ display: flex; /* For everyone else who's mainstream*/ }