How make input element take up available space next to a fixed width element?
Tags: html,css
Problem :
I'm having a bear of a time getting the following to work:
https://jsfiddle.net/1bq55L65/
I have a div
element container
, which needs to take up 100% of the available space of its parent. Then, inside it, I have a fixed-width element that needs to be pegged to the right. The remaining space to the left of the fixed-width element is to be filled with an input
text field.
My understanding is that when I set the width of an element to 100%, it computes the actual width in pixels based on the width of its parent element (in this case, the div
called expanding
). The behaviour I'm seeing, however, seems to indicate it takes the width of the parent's parent (i.e. container
)
Bonus question: how can I get the height of the fixed element to be the same height as the div
it's contained in (i.e. container
).
In either case, I'd rather avoid script if at all possible. It seems this should be a common enough requirement that CSS should accomplish it straight away.
Assume recent browsers, and in particular IE9 or later.
Solution :
Width is relative to the parent. The parent of the input
is a div
and by default div
s are block level elements, with width 100%) so as the div is 100% of it's container (the #container
div). The floating element #fixed
has no influence on the width of #expanding
in this situation.
Use a table layout or calculate the remaining space using calc
:
#container {
background-color:pink;
width:100%;
margin-top:60px
}
#fixed {
width: 70px;
text-align:center;
float:right;
background-color: #FFEEEE;
height:100%;
display:inline-block;
}
#expanding {
background-color:#FFDDDD
}
#inputField {
display:inline-block;
width:calc(100% - 70px);
box-sizing:border-box;
}
<div id="container">
<div id="fixed">Fixed</div>
<div id="expanding">
<input id="inputField" type="text" value="Type here" />
</div>
</div>
Clearly since by default input
has some UA styles you'll need to either reset these or take them in consideration (also calc
needs to be supported by the browsers you're targeting, see: http://caniuse.com/#feat=calc)..