问题描述
|
我目前有一个width:auto的div来填充整个屏幕宽度,但是我想在右侧放置一个侧边栏。
当我将width:auto div向左浮动,将固定宽度div向右浮动时,它就会向下移动。
我基本上是在寻找与reddit类似的东西,其中右边的搜索栏内容自动调整为页面宽度。
谢谢
解决方法
您可以这样:
假设您在父容器中有这2个div,它会扩展以适合页面:
<div id=\"container\">
<div id=\"autowidth\">text expands her...</div>
<div id=\"fixed\">This is a fixed column</div>
</div>
在您的CSS中:
#container {
width:100%;
border:1px solid black;
padding-right:200px;
}
#autowidth{
width:100%;
background-color:red;
float:left;
}
#fixed{
width:200px;
background-color:green;
float:right;
margin-right:-200px;
}
基本上,父容器将所有内容放在一起。它的填充为200像素(右列的宽度),因此其内容不会超出该范围。反过来,右列的边距为-200像素,因此它将强制由父填充施加的边界并将其始终置于最右端。实际上,另一个div现在仅具有由父容器提供的空间,并受其填充的限制,因此,实际上,其100%将是(100%-(父级的填充))。您可以在这里看到它的工作结果:jsfiddle。
我很确定那里可能会有更优雅的解决方案,所以请耐心等待。
如果您想提供背景,例如2列,则可以使用经典的\'faux column \'背景(请参见列表示例)
, 您严格不需要容器div。为了简洁起见,我内联了css。
<div style=\"float:right; width:14em; background-color:#CCC;\">
<p>This div is fixed-width.</p>
</div>
<div style=\"background-color:#EEE; margin-right:14.5em;\">
<p>This div is auto-width.</p>
</div>
, 答案对我不起作用,我认为它已过时。现在,您必须指定box-sizing:用于填充的border-box计入宽度,但是感谢您的启发。这是我的解决方案。
#autowidth {
float:left;
width:100%;
padding-right:200px;
box-sizing:border-box;
}
#fixed {
float:right;
width:200px;
margin-left:-200px;
}