我有2个div:一个在左边,一个在右边。左边的宽度是固定的,我想用右边的填充剩余的空间。
#搜索{ 宽度:160 px; 高度:25 px; 浮:左; background - color: # ffffff; } #{导航 宽度:780 px; 浮:左; background - color: # A53030; } < div id = "搜索" > < / div >文本 < div id = "导航" > < / div >导航
我有2个div:一个在左边,一个在右边。左边的宽度是固定的,我想用右边的填充剩余的空间。
#搜索{ 宽度:160 px; 高度:25 px; 浮:左; background - color: # ffffff; } #{导航 宽度:780 px; 浮:左; background - color: # A53030; } < div id = "搜索" > < / div >文本 < div id = "导航" > < / div >导航
当前回答
如果您试图填充flexbox中2项之间的剩余空间,请将以下类添加到您想要分离的2项之间的空div:
.fill {
// This fills the remaining space, by using flexbox.
flex: 1 1 auto;
}
其他回答
@Boushley的回答是最接近的,但是有一个问题没有解决,但已经指出了。右边的div取浏览器的整个宽度;内容采用预期的宽度。为了更好地看待这个问题:
<html>
<head>
<style type="text/css">
* { margin: 0; padding: 0; }
body {
height: 100%;
}
#left {
opacity: 0;
height: inherit;
float: left;
width: 180px;
background: green;
}
#right {
height: inherit;
background: orange;
}
table {
width: 100%;
background: red;
}
</style>
</head>
<body>
<div id="left">
<p>Left</p>
</div>
<div id="right">
<table><tr><td>Hello, World!</td></tr></table>
</div>
</body>
</html>
http://jsfiddle.net/79hpS/
内容在正确的位置(在Firefox中),但是宽度不正确。当子元素开始继承width时(例如,width: 100%的表),它们被赋予的宽度等于浏览器的宽度,导致它们溢出页面的右侧并创建一个水平滚动条(在Firefox中)或不浮动并向下推(在chrome中)。
您可以通过向右列添加overflow: hidden来轻松解决这个问题。这将为内容和div提供正确的宽度。此外,表格将接收正确的宽度,并填充可用的剩余宽度。
我尝试了上面的一些其他解决方案,它们在某些边缘情况下并不完全有效,而且太复杂了,无法进行修复。这很有效,也很简单。
如果有任何问题或顾虑,请尽管提出来。
这里有一个小的解决方案,它可以防止右列落在左列下面。更换宽度:100%;带溢出:隐藏;如果有人不知道的话,这是个棘手的解决方案。
<html>
<head>
<title>This is My Page's Title</title>
<style type="text/css">
#left {
float: left;
width: 180px;
background-color: #ff0000;
}
#right {
overflow: hidden;
background-color: #00FF00;
}
</style>
</head>
<body>
<div>
<div id="left">
left
</div>
<div id="right">
right
</div>
</div>
http://jsfiddle.net/MHeqG/2600/
[编辑]还有一个三列布局的例子: http://jsfiddle.net/MHeqG/3148/
/* * css * /
#search {
position: absolute;
width: 100px;
}
.right-wrapper {
display: table;
width: 100%;
padding-left:100px;
}
.right-wrapper #navigation {
display: table-cell;
background-color: #A53030;
}
/* * html * /
<div id="search"></div>
<div class="right-wrapper">
<div id="navigation"></div>
</div>
尝试添加相对位置,删除右边的宽度和浮动属性,然后添加0值的左和右属性。
此外,您还可以添加左距规则,其值基于左元素的宽度(如果您需要在两者之间留出空间,则要加上一些像素)来保持其位置。
这个例子对我来说很有用:
#search {
width: 160px;
height: 25px;
float: left;
background-color: #FFF;
}
#navigation {
display: block;
position: relative;
left: 0;
right: 0;
margin: 0 0 0 166px;
background-color: #A53030;
}
物品和容器的规则;
Container: {*** display: table; ***}
Items: {*** display: table-cell; width: 100%; ***}
使用空白:nowrap;为最后一项的文本进行解构。
项目X% |项目Y% |项目Z%
总长度总是= 100%!
if
Item X=50%
Item Y=10%
Item z=20%
然后
项目X = 70%
项目X占主导地位(在表格CSS布局中,第一项占主导地位)!
试着max-content;用于在容器中传播div的div内部属性:
div[class="item"] {
...
width: -webkit-max-content;
width: -moz-max-content;
width: max-content;
...
}