Gre*_*Cat 14 html css html-table css-float
我有一个看起来像这样的身体的网站:
<body>
<div id="header">...</div>
<div id="content">...</div>
<div id="footer">...</div>
</body>
Run Code Online (Sandbox Code Playgroud)
在这些div
s中没有使用绝对/相对定位技巧,但是这些s及其内部元素的样式中有很多float
s,clear
s,margin
s和padding
s div
.所有这些都会产生一个看起来像这样的网站:
?????????????????
? header ?
?????????????????
?????????????????
? content ?
?????????????????
?????????????????
? footer ?
?????????????????
Run Code Online (Sandbox Code Playgroud)
我的问题是:如何添加一个独立的固定宽度左栏(侧栏),其中包含额外的内容,这些内容将收缩整个站点(页眉内容页脚)并将它们移到右侧.
?????????????????
?side?? header ?
?bar ????????????
? ????????????
? ?? content ?
? ????????????
? ????????????
? ?? footer ?
?????????????????
Run Code Online (Sandbox Code Playgroud)
我知道一个几乎理想的解决方案,但它很丑陋,需要重新嵌套现有的div:
<body>
<table>
<tr>
<td id="sidebar">...</td>
<td>
<div id="header">...</div>
<div id="content">...</div>
<div id="footer">...</div>
</td>
</tr>
</table>
</body>
Run Code Online (Sandbox Code Playgroud)
是否可以优雅地做到这一点,只需在身体的某处添加一个外部侧边栏元素,即,像那样?
<body>
<div id="sidebar">...</div>
<div id="header">...</div>
<div id="content">...</div>
<div id="footer">...</div>
</body>
Run Code Online (Sandbox Code Playgroud)
我尝试过天真的方法 - 比如样式:
#sidebar { float: left; width: 20em; }
Run Code Online (Sandbox Code Playgroud)
要么
#header { margin-left: 20em; }
#content { margin-left: 20em; }
#footer { margin-left: 20em; }
Run Code Online (Sandbox Code Playgroud)
这种工作,但它在标题/内容/页脚中很快就会中断clear: both
或clear: left
遇到.
那么,表解决方案有什么替代方案吗?
Gar*_*yon 13
我喜欢使用绝对定位的侧边栏,然后将包装上的填充设置为该元素的宽度.然后我要么在其他元素上设置margin-padding,要么将它添加到包装器的padding上.
<div class="container">
<div id="sidebar"></div>
<div id="header"></div>
<div id="content"></div>
<div id="footer"></div>
</div>
Run Code Online (Sandbox Code Playgroud)
.container { position:relative; padding:0 0 0 55px; }
#sidebar {
position:absolute;
top:0; bottom:0; left:0;
width:50px;
background:#000;
}
#header { border:1px solid #000; width:100px; height:20px;
margin:0 0 5px 0;
}
#content { border:1px solid #000; width:100px; height:50px;
margin:5px 0 5px 0;
}
#footer { border:1px solid #000; width:100px; height:20px;
margin:5px 0 0 0;
}
Run Code Online (Sandbox Code Playgroud)
我使用HTML5元素来给出标记的语义含义.
<body>
<aside><!-- Nav bar --></aside>
<article>
<header>...</header>
<section>...</section>
<footer>...</footer>
</article>
</body>
Run Code Online (Sandbox Code Playgroud)
然后,风格aside
和article
用float: left
.