3

我想要一个 html/css 布局,它有一个 div#header 和 div#body 作为 body 标记的直接子级。我希望 div#body 填充剩余空间,并且我不想使用 JavaScript。我知道如果你知道 div#header 的确切高度是可能的。但我不想解决这个问题。

固定 div#header 的示例

<head>
    <style>
        html, body {
            position: relative;
            margin: 0;
            padding: 0;
            width: 100%;
            height: 100%;
        }

        div {
            width: 100%;
        }
        #header {
            position: relative;
            <!-- i want to remove height because i want the header to size itself 
                 dependent on it's content -->
            height: 100px;
            background-color: red;
        }

        #body {
            <!-- I want to make the body position relative and set top to 0 
                 but that does not work as expected.-->
            position: absolute;
            top: 100px;

            margin: 0;
            bottom: 0;
            background-color: green;
            height: auto;
        }
    </style>
</head>

<body>
    <div id="header">header</div>
    <div id="body">body</div>
</body>

请让我知道是否有任何使用 div 和 css 的替代方案。提前谢谢了!

4

3 回答 3

2

这是更新的答案:我所做的是让父 html 和 body 显示为表格,其他div 具有表格行的属性,这个 css 将使它们捕获整个屏幕区域。

现在我已经给出了 auto 的标题高度。

#body 正在继承另一个空间。

试试这个:http: //jsbin.com/ezozeb/5/edit

html, body {
   margin: 0;
   padding: 0;
   width: 100%;
   height: 100%;
   display:table;
}

#header {
  background-color: red;
  display:table-row;
  height:auto;
}
#body {
  background-color: green;
  display:table-row;
  height:inherit;
}
于 2012-11-16T15:01:01.870 回答
2

您可以将min-heightbody div 的 设置100%为伸展 body div(我更改了 body bg 颜色以使其更明显)。

但是,我对您的第二个要求不是 100% 清楚 ( <!-- I want to make the body position relative and set top to 0 but that does not work as expected.-->)

在这里提琴

于 2012-11-16T14:17:52.180 回答
0

首先,删除body元素的高度和宽度。

您可以使用页面包装器来实现这一点:

#PageWrapper
{
  width: 844px;
  background-color: ##4628C4;
  margin: auto;
}

#PageContentWrapper
{
  width: 659px;
  float: left;
  background-color: #e1e1e1;
  min-height: 500px;
  padding: 10px;
}

pagecontentwrapper 将最小高度设置为 500px。然后在 html 中,您可以将这些标识符分配给 body 和 div

<html>
  <head>
    <link...>
  </head>
  <body id="PageWrapper">

    <div id="PageContentWrapper">
      Content of the body
    </div>
   </body>
</html>

如果要使 div 可滚动,则应定义高度和/或宽度并将其添加到 css:

overflow-x:auto; <!--horizontal-->
overflow-y:auto; <!--vertical-->

例如,如果您将 pagewrappers 的高度设置为 1000(不是 min-heigt)并且 overflow-y: auto; 然后当内容超出范围时会出现滚动条。

如果你想让标题总是在顶部,你应该应用这样的东西:

#PageWrapper
{
  width: 844px;
  background-color: ##4628C4;
  margin: auto;
}

#Header
{
  background-color:#aaaaaa;
  width: 844px;
  height: 240px;
}

#PageContentWrapper
{
  width: 659px;
  height: 700px;
  overflow-y: auto;
  float: left;
  background-color: #e1e1e1;

  padding: 10px;
}

并在 html

<html>
  <head>
    <link...>
  </head>
<body id="PageWrapper">
  <div id=Header>
    Headertext
  </div>  
  <div id="PageContentWrapper">
    Content of the body
  </div>
</body>
</html>
于 2012-11-16T14:17:51.827 回答