2010-02-03 20 views
1

更好地标记说明:在2列布局中,如果我删除另一列,如何将一列扩展为总宽度?

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扩展取代侧边栏:

​​

回答

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,你将需要知道你的侧边栏有多宽。这是可以解决的,但因为这是不是真的你的问题,我不会告诉你如何班门弄斧,我敢肯定,你可以工作了;)

0

这一个是棘手:

如果您在侧边栏上设置宽度,将其浮动,并且不要在内容上设置宽度(也请不要浮动内容,因为这会导致div“收缩” )。然后该列将按照您的期望行事。

#content { width: auto; display:block } /* not really necessary as these are default */ 
#sidebar { width: 30%; float: right } 

我想补充一点,这本质上是片状的,通常是限制性的。你最好的选择是,如果你控制服务器端的布局(你有一些脚本可以生成布局),那么在呈现之前在文档中附加CSS类。

纯html解决方案是可能的,但它也依赖于这种特定的行为。如果您想浮动#content div,它将不起作用(因为您将被迫指定尺寸以避免收缩包装效果)。

你也可以使用javascript来做到这一点。事情要注意有可能会得到一个FOUC(的无样式内容闪烁)作为的JavaScript踢英寸

使用jQuery你可以做这样的事情算相邻的div即

jQuery('#content').nextAll().length 

然后使用结果做这样的事情:

jQuery('#content').addClass('has_sidebar'). 
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的工作。 但是你想真的去做。

2

纯CSS方法将使用CSS表格的布局:

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(如本文其他答案所述)作为后备将是理想的。

相关问题