简体   繁体   中英

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

Consider a parent <div> which is position:relative; width:100% 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.

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> 

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM