Andreas Linden
Andreas Linden

Reputation: 12721

CSS let input consume available width

I have the following markup as a base:

<div>
    <span>some dynamic text</span>
    <input type="text" />
</div>

I want the input to be displayed in a line with the text (which is always a single line but varying in length) and consume the available width according to the text length. the markup can be changed if required. both elements should be 100% of the parent element's width.

Upvotes: 2

Views: 376

Answers (1)

Chris
Chris

Reputation: 26878

Two methods I can think of:

The first one:

You can simulate the behavior of a table using CSS;

HTML:

<div class = "container">
    <div class = "text">Glee is awesome!</div>
    <div class = "inputtext"><input type="text" /></div>
</div>

CSS:

.container {
    display: table;
    width: 100%; /*how much should both the text and the input take*/
}
.container .text {
    white-space: nowrap;
    display: table-cell;
    width: 1px; /*make sure it's only as wide as needed*/
}
.container .inputtext {
    display: table-cell;
}
.container input {
    width: 100%; /*let the input take all available space*/
}

Little demo: little link.

The second one:

This method relies on floating:

HTML:

<div class = "text">Glee is awesome!</div>
<div class = "inputtext"><input type = "text" /></div>

CSS:

.text {
    float: left;
}
.inputtext {
    overflow: hidden; /*this is the key here*/
}
input {
    width: 100%;
}

Another little demo: little link.

Upvotes: 2

Related Questions