所有其他答案(截至2020年9月10日)都集中在将填充添加到.content DIV 使其大于所需的70%,导致它被推到.sidebar DIV下面,然后尝试使DIV大小为70%,包括填充。最简单的答案是不要填充.content DIV(因此它保持在.container DIV的70%),而是填充其中的P。没有宽度规定,内部的P是DIV的100%,包括填充,因此P的文本将相应地压缩(到.content DIV的100% - 每侧10px)。所以改变
.content {
background-color: YELLOW;
float: left;
width: 70%;
padding: 10px;}
到
.content {
background-color: YELLOW;
float: left;
width: 70%;}
.content p {
padding: 10px;}
或者,将box-sizing: border-box
添加到.content样式中,可以改变尺寸计算方式以包括填充,但这是CSS3,而将填充移入P在早期版本中有效。(还有人在使用吗?)
经过测试,我只有一个(修辞性的)问题。为什么要同时浮动两个DIV?如果您只浮动.sidebar DIV,那么.content DIV中的额外文本将流动到其下方(宽度现在从.container DIV的左侧边缘开始)。通过同时浮动两个,.content DIV中的额外文本保持在右侧,留下了.sidebar DIV下方的空白区域(如果其中的内容少于.content DIV)。我认为这是有意图的,但这与使用双列表格产生完全相同的效果。
<html>
<head>
<style>
.table_container {
width: 100%;
max-width: 960px;
background-color: RED;}
.table_sidebar {
background-color: GREEN;
width: 30%;}
.table_content {
background-color: YELLOW;
width: 70%;
padding : 10px;}
</style>
</head>
<body>
<table class="table_container">
<tr>
<td class="table_sidebar">text in sidebar</td>
<td class="table_content">text in content</td>
</tr>
</table>
</body>
</html>
这种方法与原始的(浮动的DIV)解决方案有一些细微的差别。
- 每个单元格周围都有一个小间隙。
- 侧边栏与内容高度相同。
- 表格的高度仅为其内容高度(可能小于指定的200px)。
- TD的内容没有上下边距(在DIV中的默认CSS为P)。
可以按以下方式进行修复:
- 在
.table_container
中添加 border-spacing:0
,并且对于旧版本的浏览器,添加 cellspacing="0"
作为 TABLE 的属性。
- 给内容 TD 添加
rowspan="2"
,在侧边栏 TD 下方添加一个空的 TD,并通过在 .table_sidebar
中添加 height:1px
强制将侧边栏 TD 的高度设置为最低。
- 将表格封装在所需高度的 DIV 中。
- 在 TD 中添加具有明确定义的上下边距的 P 元素(默认情况下,TD 中的 P 的 CSS 显然没有边距)。
<html>
<head>
<style>
.container {
max-width: 960px;
background-color: RED;
height: 200px;}
.table_container {
width: 100%;
background-color: RED;
border-spacing: 0;}
.table_sidebar {
background-color: GREEN;
width: 30%;
height: 1px;}
.table_content {
background-color: YELLOW;
padding : 10px;}
td p {
margin: 1em 0;}
</style>
</head>
<body>
<div class="container">
<table class="table_container" cellspacing="0">
<tr>
<td class="table_sidebar"><p>text in sidebar</p></td>
<td rowspan="2" class="table_content"><p>text in content</p></td>
</tr>
<tr><td></td></tr>
</table>
</div>
</body>
</html>
虽然两种方法都可以产生相同的输出,但TABLE方法不太依赖于尺寸的准确性。