代码之家  ›  专栏  ›  技术社区  ›  ProfK

如何扩展输入以占用div中的剩余空间

  •  1
  • ProfK  · 技术社区  · 8 年前

    我想创建一个下拉菜单,下拉一个自定义面板(div),而不是一个选项列表。这个面板无关紧要,因为它与我要问的布局无关。对于基本下拉视图,我有以下内容:

    <style>
        .folder-selection {
            width: 100%;
        }
        .dropdown-button {
            float: right;
        }
    </style>
    
        <div id=container>
            <input type="text" class="folder-selection" />
            <button type="button" class="dropdown-button">...</button>
        </div>
    

    现在我知道float和width 100%不正确,但我有一个container div,左边有一个输入,右边有一个按钮。按钮必须固定在输入的右侧。如果容器很窄,则输入必须很窄,反之亦然,但我希望在设计时不知道容器的宽度就可以实现这一点。

    容器应适合任何宽度,输入的宽度应相应调整。就像普通人一样 select 元素,其中文本部分始终填充其右侧下拉图标/按钮未占用的所有空间。

    3 回复  |  直到 8 年前
        1
  •  2
  •   Himanshu Gupta    8 年前

    下面的例子将帮助您。让我知道,如果你不想固定宽度的图标在右侧,所以我会相应地更新此代码。

    #container {
    	position: relative;
    	border: 1px solid #ccc;
    	padding: 5px 40px 5px 5px;
    	margin: 0 0 10px;
    }
    .folder-selection {
    	width: 100%;
    	padding: 5px;
    	border: none;
    	box-sizing: border-box;
    	height: 30px;
    }
    .dropdown-button {
    	position: absolute;
    	top: 5px;
    	right: 5px;
    	height: 30px;
    }
    <div id=container>
     <input type="text" class="folder-selection" />
     <button type="button" class="dropdown-button">...</button>
    </div>
        2
  •  1
  •   Cons7an7ine    8 年前
    <style>
    .dropdown-button {
        width: 16px;  /*Set width of button*/
    }
    
    .folder-selection {
        width: calc(100% - 16px); /*div's width minus button's width*/
    }
    </style>
    
    <div id=container>
        <input type="text" class="folder-selection" /><!-- this comment is to remove white space between the two elements
    --><button type="button" class="dropdown-button">...</button>
    </div>
    

    只要在运行时知道按钮的宽度,就不必设置按钮的宽度。

        3
  •  -1
  •   sajee    8 年前

    此代码将帮助您按预期定位元素。

    * {
      box-sizing: border-box;
    }
    
    .dropdown-container {
      width: 500px;
      display: table;
      background: orange;
    }
    
    .dropdown-container .input-container {
      display: table-cell;
    }
    
    .dropdown-container .input-container input {
      width: 100%;
      padding-right: 10px;
    }
    
    .dropdown-container .button-container {
      display: table-cell;
      width: 150px;
    }
    
    .dropdown-container .button-container button {
      width: 100%;
    }
    <div class="dropdown-container">
      <div class="input-container">
        <input type="text" class="folder-selection" />
      </div>
      <div class="button-container">
        <button type="button" class="dropdown-button">Drop</button>
      </div>
    </div>