CSS填充剩余宽度

新手上路,请多包涵

我有这个标题栏。

 <div id="header">
        <div class="container">
            <img src="img/logo.png"/>
            <div id="searchBar">
                <input type="text" />
            </div>
            <div class="buttonsHolder">
                <div class="button orange inline" id="myAccount">
                    My Account
                </div>
                <div class="button red inline" id="basket">
                    Basket (2)
                </div>
            </div>

        </div>
    </div>

我需要 searchBar 来填补 div 中剩余的空白。我该怎么做?

这是我的 CSS

 #header {
    background-color: #323C3E;
    width:100%;
}

.button {
    padding:22px;
}

.orange {
    background-color: #FF5A0B;
}

.red {
    background-color: #FF0000;
}

.inline {
    display:inline;
}

#searchBar {
    background-color: #FFF2BC;
}

原文由 TMH 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 903
2 个回答

您可以使用 CSS 表格单元格来实现此布局。

稍微修改您的 HTML,如下所示:

 <div id="header">
    <div class="container">
        <div class="logoBar">
            <img src="http://placehold.it/50x40" />
        </div>
        <div id="searchBar">
            <input type="text" />
        </div>
        <div class="button orange" id="myAccount">My Account</div>
        <div class="button red" id="basket">Basket (2)</div>
    </div>
</div>

只需删除两个 .button 元素周围的包装元素。

应用以下 CSS:

 #header {
    background-color: #323C3E;
    width:100%;
}
.container {
    display: table;
    width: 100%;
}
.logoBar, #searchBar, .button {
    display: table-cell;
    vertical-align: middle;
    width: auto;
}
.logoBar img {
    display: block;
}
#searchBar {
    background-color: #FFF2BC;
    width: 90%;
    padding: 0 50px 0 10px;
}

#searchBar input {
    width: 100%;
}

.button {
    white-space: nowrap;
    padding:22px;
}

应用 display: table.container 并给它 100% 的宽度。

对于 .logoBar , #searchBar , .button , 应用 display: table-cell .

对于 #searchBar ,将宽度设置为 90%,这会强制所有其他元素计算缩小以适应宽度,并且搜索栏将扩展以填充其余空间。

根据需要在表格单元格中使用 text-align 和 vertical-align。

参见演示:http: //jsfiddle.net/audetwebdesign/zWXQt/

原文由 Marc Audet 发布,翻译遵循 CC BY-SA 3.0 许可协议

使用 calc

https://jsbin.com/wehixalome/edit?html,css,输出

HTML:

 <div class="left">
  100 px wide!
  </div><!-- Notice there isn't a space between the divs! *see edit for alternative* --><div class="right">
    Fills width!
  </div>

CSS:

 .left {
  display: inline-block;
  width: 100px;

  background: red;
  color: white;
}
.right {
  display: inline-block;
  width: calc(100% - 100px);

  background: blue;
  color: white;
}

更新:作为 div 之间没有空格的替代方法,您可以在外部元素上设置 font-size: 0

原文由 Isaiah Turner 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题