我有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 >导航
当前回答
我在Boushley的答案中发现的问题是,如果右列比左列长,它就会围绕着左列并继续填充整个空间。这不是我想要的行为。在搜索了许多“解决方案”后,我找到了一个教程(现在链接死了),如何创建三列页面。
作者提供了三种不同的方法,一种是固定宽度,一种是三个可变列,一种是固定外列,中间可变宽。比我发现的其他例子更加优雅和有效。显著提高了我对CSS布局的理解。
基本上,在上面的简单例子中,将第一列向左浮动,并给它一个固定的宽度。然后给右边的一列留出比第一列稍宽的左距。就是这样。完成了。Ala Boushley的代码:
下面是Stack Snippets & jsFiddle中的一个演示
#{离开 浮:左; 宽度:180 px; } #{正确 margin-left: 180 px; } /*只是为了突出div,例如*/ #left {background-color:粉色;} #right {background-color:浅绿色;} <div id="left"> left </div> . <div id="right"> right </div> .
在鲍什利的例子中,左边一列表示右边另一列。只要左列结束,右列就开始再次填充整个空间。在这里,右列只是进一步对齐到页面中,而左列占据了它的大空白。不需要流交互。
其他回答
/* * 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>
物品和容器的规则;
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;
...
}
@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提供正确的宽度。此外,表格将接收正确的宽度,并填充可用的剩余宽度。
我尝试了上面的一些其他解决方案,它们在某些边缘情况下并不完全有效,而且太复杂了,无法进行修复。这很有效,也很简单。
如果有任何问题或顾虑,请尽管提出来。
现在,您应该使用flexbox方法(可以适用于所有带有浏览器前缀的浏览器)。
.container {
display: flex;
}
.left {
width: 180px;
}
.right {
flex-grow: 1;
}
更多信息:https://css-tricks.com/snippets/css/a-guide-to-flexbox/
我也遇到过类似的问题,我在这里找到了解决方案: https://stackoverflow.com/a/16909141/3934886
解决方案是一个固定的中心div和液体边列。
.center{
background:#ddd;
width: 500px;
float:left;
}
.left{
background:#999;
width: calc(50% - 250px);
float:left;
}
.right{
background:#999;
width: calc(50% - 250px);
float:right;
}
如果你想要一个固定的左列,只需相应地改变公式。