在我的网站上,我有 3 个 div、1 个标题、1 个主要内容和右侧的侧边栏。 侧边栏才是真正的问题。我希望侧边栏始终粘在浏览器窗口的右侧,并且如果用户调整窗口大小以使宽度低于主栏和侧边栏,侧边栏将停止在主要内容的左边缘。
当用户首次访问网页并至少在 Mac 上按下“绿色最大化窗口按钮”时,窗口应调整大小,以便主要内容和侧边栏无间隙地边对边放置。
使用我的代码,一切正常,除了当我将窗口大小调整到可能的最小宽度然后按最大化窗口按钮时,两个 div 之间有 16px 的间隙。
我的代码:
HTML:
<div id="header">Header</div>
<div id="container">
<div id="main">
<p> Left </p>
</div>
<div id="sidebar">
<p> Right </p>
</div>
</div>
CSS:
body{
margin:0 0;
min-width:606px;
}
#header {
padding:5px 10px;
background:#00FF00;
height:100px;
}
#container{
min-width: 865px;
min-height: 50px;
}
#main {
float:left;
min-width: 622px;
background:#FF0000;
}
#sidebar {
float:right;
width:243px;
min-height: 50px;
background:#0000FF;
margin-bottom: -20px;
}
最佳答案
引用: jsFiddle (在地址栏中删除 /show/
以访问 jsFiddle 编辑页面。)
不要在布局中使用float
,而是使用table
和table-cell
来实现您的目标。在 XP 机器上的 Firefox、Chrome、IE8 中测试并运行。
HTML:
<div id="header">Header</div>
<div id="container">
<div id="main">
<p>Main</p>
</div>
<div id="sidebar">
<p>Sidebar</p>
</div>
</div>
CSS:
body{
margin: 0 auto;
padding: 0;
}
#header {
background: green;
height: 100px;
min-width: 865px; /* Optional: This size is the same as #container width. */
}
#container{
display: table;
width: 100%;
min-width: 865px;
height: 50px;
}
#main {
display: table-cell;
/*min-width: 622px;*/ /* Not needed since #container min-width less #sidebar width will use remainder percentage space (since #container is set at 100%) */
height: 100%; /* Maximum height is set via #container height */
background: red;
}
#sidebar {
display: table-cell;
width: 243px; /* The fixed width of the sidebar */
height: 100%; /* Maximum height is set via #container height */
background: aqua;
}
关于css - 左/右浮动在窗口调整大小时产生间隙,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11678626/