用标记更好地解释:
HTML:
<div><!--both sidebar and content share width-->
<div id="content"><!--maybe at 30%-->
</div>
<div id="sidebar"><!--may be at 70%-->
</div>
</div>
CSS:
#sidebar{float:left;} /* no idea what width*/
#content{float:right;} /* no idea what width*/
我想要做的是,如果标记中没有侧边栏,则内容div会扩展为取代侧边栏:
<div>
<div id="content"><!--width now at 100%-->
</div>
</div>
答案 0 :(得分:2)
纯CSS方法将使用CSS table-layout:
CSS:
#wrapper{
display: table;
width: 100%;
}
#content {
display: table-cell;
width: auto;
}
#sidebar {
display: table-cell;
width: 30%;
}
HTML:
<div id="wrapper"><!--both sidebar and content share width-->
<div id="content"><!--maybe at 30%-->content
</div>
<div id="sidebar"><!--may be at 70%-->sidebar
</div>
</div>
上述内容不适用于IE6 / 7等老款浏览器。使用javascript(如本文其他答案中所述)作为后备将是理想的。
答案 1 :(得分:0)
这个很棘手:
如果你在侧边栏上设置宽度,浮动它,并且不在内容上设置宽度(同样,不要浮动内容,因为这会导致div“收缩包装”)。然后该列的行为将如您所愿。
#content { width: auto; display:block } /* not really necessary as these are default */
#sidebar { width: 30%; float: right }
我想补充一点,这本质上是片状的并且经常是限制性的。你最好的选择是,如果你控制服务器端的布局(你有一些生成布局的脚本),那么在文档渲染之前将css类附加到文档中。
纯HTML解决方案是可行的,但它也依赖于这种特殊行为。如果你想浮动#content div,它将不起作用(因为你将被迫指定尺寸以避免收缩包装效果)。
您也可以使用javascript执行此操作。需要注意的是,随着javascript的推出,你可能会得到一个FOUC(闪烁的无格式内容)。
使用jQuery,你可以做一些事情,比如计算相邻的div,即。
jQuery('#content').nextAll().length
然后使用结果执行以下操作:
jQuery('#content').addClass('has_sidebar').
答案 2 :(得分:0)
如果你像这样翻转你的div,你可以实现这个:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Fluid Columns</title>
<style type="text/css">
<!--
div{height:100px; margin-bottom: 50px; color: #fff;}
#sidebar{float:left;background: red;} /* no idea what width*/
#content{background: blue;} /* no idea what width*/
-->
</style>
</head>
<body>
<div><!--both sidebar and content share width-->
<div id="sidebar"><!--may be at 30%-->
Sidebar
</div>
<div id="content"><!--maybe at 70%-->
Partial Width
</div>
</div>
<div>
<div id="content"><!--width now at 100%-->
Whole Width
</div>
</div>
</body>
</html>
此方法的唯一缺点是,如果要向内容div添加任何填充,则需要知道侧边栏的宽度。这是可以解决的,但因为那不是你的问题,我不会告诉你如何吸蛋,我相信你可以解决它;)
答案 3 :(得分:0)
功能:
<script type='text/javascript'>
/**** Minimising ****/
function Minimise()
{
document.getElementById('FirstColumn').style.width = '0%';
document.getElementById('SecondColumn').style.width = '100%';
}
/**** Expanding ****/
function Maximise()
{
document.getElementById('FirstColumn').style.width = '50%';
document.getElementById('SecondColumn').style.width = '50%';
}
</script>
运行功能
<a href="javascript:Minimise();">Click here to minimise column1 etc</a>
然后,您可以随时添加样式块以隐藏所有内容或您需要执行的任何操作。 你也可以使用切换,但这种方式使用div可以很好用。 但是你真的想要去做。
答案 4 :(得分:0)
看看这个技巧:
http://www.webdesignerwall.com/tutorials/css-clearing-floats-with-overflow/
它非常灵活,不需要服务器端代码。 IMO的东西应该分开,服务器端 - 服务器端任务,前端 - 用于前端任务。
祝你好运