Elimination
Elimination

Reputation: 2723

Make a div and a input width to be 100% of the parent

Consider a parent <div> which is position:relative; width:100%. It contains a <div> and a <input>. I want them to have together a 100% width.

The <div> ideally should be fixed (it's a custom button) and the <input> should fill the rest of the width (think about window resizing).

Is it possible doing it without involving JS code?

Also, it's not a "must-have" but I wish to support as for as I can with IE7+.

CODE:

<div id="parent" style="position:relative; width:100%">
  <div id="button">Click</div>
  <input type="text" id="txt_input" />
</div>

CLARIFICATION:
I am able to use javascript of course. If there isn't an elegant solution, then JS it is. Let me know please.

Upvotes: 2

Views: 1846

Answers (3)

Wesley Cheek
Wesley Cheek

Reputation: 1726

This is the minimum I needed to make the child input element the same size as the parent:

.parent {
position: relative;
}

.child {
position: absolute;
width: 100%;
height: 100%;
right: 0;
top: 0;
}
<div class="parent">
  <input type="text" class="child" />
</div>

Upvotes: 1

CupawnTae
CupawnTae

Reputation: 14600

You can do it without requiring extra HTML elements. For modern browsers, use flexbox. Here's a great list of browser support for flexbox http://caniuse.com/#feat=flexbox.

#parent {
    display:flex;
}
#button {
  width:100px;
  background:red;
}
#txt_input {
  flex: 2;
}
<div id="parent" style="position:relative; width:100%">
  <div id="button">Click</div>
  <input type="text" id="txt_input" />
</div>

And for older browser support, you can use table layout instead:

#parent {
  display:table;
}
#button {
  background:red;
  display:table-cell;
  width:100px;
}
#txt_input {
  display:table-cell;
  width:100%
}
<div id="parent" style="position:relative; width:100%">
  <div id="button">Click</div>
  <input type="text" id="txt_input" />
</div>

Upvotes: 1

Daniel Cheng
Daniel Cheng

Reputation: 870

In this case, box-sizing: border-box comes in handy. Let's assume the width of your button is 150px.

<div id="parent" style="position:relative; width:100%; padding-left: 150px; box-sizing: border-box;">
    <div id="button" style="position: absolute; top: 0; left: 0; width: 150px">
        Click
    </div>
    <div>
        <input type="text" id="txt_input" style="width: 100%" />
    </div>
</div>

Upvotes: 3

Related Questions