[英]Fill remaining width inside parent that is also filling remaining width
我有一个固定大小的导航栏(使用Bootstrap ),包含四个div。 这些div包含徽标,一些链接/下拉菜单和搜索框:
┌────────────────────────────navbar (fixed-size)──────────────────────────────┐
│┌───logo───┐┌───dropdown───┐┌───────────links──────────┐┌────search box─────┐│
││fixed-size││ fixed-size ││ variable width ││ fill remaining ││
│└──────────┘└──────────────┘└──────────────────────────┘└───────────────────┘│
└─────────────────────────────────────────────────────────────────────────────┘
我想要搜索框(最右边的框)填充容器中的剩余空间。 搜索框包含一个输入和一个按钮:
┌─────────────────────────────────┐
│┌─────────────────────┐┌────────┐│
││ <input> ││<button>││
│└─────────────────────┘└────────┘│
└─────────────────────────────────┘
该按钮具有固定的大小,但我希望输入水平缩放,拉伸搜索框以填充其父级(导航栏)。
编辑:为了澄清,我希望搜索框占据其兄弟姐妹(徽标,下拉列表和链接)占用空间时留下的(水平)空间。 由于搜索框是由输入和按钮组成的,而按钮的宽度是固定的,我希望输入扩展并按下搜索框的边界,直到搜索框填满它在导航栏中留下的兄弟姐妹的空间
我就是这样做的: http : //jsfiddle.net/vU52q/
你有你的包装和子元素:
<div class="search">
<input type="text" />
<button type="submit">Go</button>
</div>
然后将容器设置为position: relative;
和你的提交按钮到position: absolute;
并为容器提供足够的填充按钮。
.search {
box-sizing: border-box;
background: #0f0;
padding: 5px 100px 5px 5px;
position: relative;
width: 300px;
}
.search input {
width: 100%;
}
.search button {
position: absolute;
top: 5px;
right: 5px;
width: 85px;
}
这样,输入始终是父元素的宽度减去固定宽度按钮的宽度。
你也可以使用内联对齐和css calc
,但这是我的首选方式。
如果你想使用calc,你可以检查一下,它可能提供更多的选项来添加额外的固定大小元素: http : //jsfiddle.net/ug7a9/
这会考虑每个部分并明确地将其添加到宽度计算中。
<div class="search">
<button type="submit">Go</button><!--
--><button type="submit">Go</button><!--
--><input type="text" /><!--
--><button type="submit">Go</button>
</div>
这些注释用于防止.search
元素之间的元素之间的空间(您也可以使用font-size:0)。
* {
box-sizing: border-box;
}
.search {
background: #0f0;
position: relative;
width: 300px;
}
.search input {
display: inline-block;
width: calc(100% - 50px - 50px - 50px);
}
.search button {
display: inline-block;
width: 50px;
}
你希望你的选择器更明确一些(即不要做*
),但为了快速演示,我把它放进去了。
我最终改变了我的代码,并将评论中提供的解决方案中的想法用于他的答案。 我还使用了他绝对定位的按钮技巧。 这就是我做的:
我在搜索框中使用了一个范围,并将按钮从搜索框中直接移到导航栏中:
<nav>
...
<span>
<input type="text" placeholder="Search...">
</span>
<button class="searchBtn" type="button"></button>
</nav>
使用这个css:
span {
display: block; /*This is the trick from*/
overflow: hidden; /*the solution Chad provided*/
}
input {
width: 100%;
padding-right: 65px; /*This is to make room*/
} /*for the button*/
button {
position: absolute;
right: 0px;
top: 0px;
}
overflow: hidden
在跨度上使一切成为可能。 在这里阅读: http : //colinaarts.com/articles/the-magic-of-overflow-hidden/#making-room-for-floats
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.