填充至少100%页面高度

时间:2015-06-05 21:14:13

标签: html css

容器如何一起填充至少100%的页面高度,但如果它们适合则不超过100%?

这是plunker

  html, body {
    height: 100%;
  }

  section {
    margin: 0;
    min-height: 100%;
  }

如果有<section>但不是几个,那么看起来很好:

    <section style="background: olive">Hi</section>
    <section style="background: tomato">Hello</section>
    <section style="background: olive">Hey</section>

正文内容应填写页面高度的100%(因此它们各占约33%),此处min-height不是一个选项。

通常页面内容足够高,并且不需要高度样式规则,但如果该部分在页面上是独立的(并且取决于分辨率),则情况并非如此。

背景图片可能会有所不同,我不能让身体颜色与上一部分相同。

可以单独用CSS完成吗?

5 个答案:

答案 0 :(得分:4)

您可以尝试CSS表格布局。

JsFiddle Demo

&#13;
&#13;
html, body {
    height: 100%;
}
body {
    display: table;
    width: 100%;
    margin: 0;
}
section {
    display: table-row;
}
&#13;
<section style="background: olive">Hi</section>
<section style="background: tomato">Hello</section>
<section style="background: olive">Hey</section>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

这可以使用flexbox和视口单位或百分比来实现,以在身体上设置高度。

注意:Safari仍需要前缀。

另请注意:我认为所有css解决方案(包括flexbox和table display)都会出现问题,一旦内容溢出页面高度,这些部分的高度将不相同。我唯一能想到让它看起来可以接受的是给这些部分一个最小高度,例如min-height: 20vh;min-height: 200px;

此代码段显示了它将如何结束。

html,
body {
  margin: 0;
  min-height: 100vh;
}
body {
  display: -webkit-flex;
  display: flex;
  -webkit-flex-direction: column;
  flex-direction: column;
}
section {
  -webkit-flex: 1;
  flex: 1;
}
<!DOCTYPE html>
<html>

<head>

</head>

<body>
  <section style="background: olive">Hi</section>
  <section style="background: tomato">Hello</section>
  <section style="background: olive">Hey</section>
</body>

</html>

此代码段显示了如果容器的内容将容器拉伸超过页面的整个高度,它将如何结束。

html,
body {
  margin: 0;
  min-height: 100vh;
}
body {
  display: -webkit-flex;
  display: flex;
  -webkit-flex-direction: column;
  flex-direction: column;
}
section {
  -webkit-flex: 1;
  flex: 1;
}
<!DOCTYPE html>
<html>

<head>

</head>

<body>
  <section style="background: olive">Hi</section>
  <section style="background: tomato">Hello
    <p>Here<p>is<p>my<p>really<p>long<p>section<p>see<p>what<p>happens?
  </section>
  <section style="background: olive">Hey
    <p>This<p>section<p>is<p>really<p>long<p>too<p>!
  </section>
</body>

</html>

答案 2 :(得分:0)

您可以尝试使用flexbox布局,但并非所有浏览器都支持此功能:

https://css-tricks.com/snippets/css/a-guide-to-flexbox/

答案 3 :(得分:0)

如果我正确地阅读你的问题,你希望身体的最大高度为视口的100%,然后你想要扩展许多部分来填充整个视口?

这样做的简单方法是告诉他们有多少人在那里。例如:

<body class="three-sections">

<section class="three-sections" style="background: olive">Hi</section>
<section class="three-sections" style="background: tomato">Hello</section>
<section class="three-sections" style="background: olive">Hey</section>

如果您不想告诉该页面有多少部分,您可以查找:nth-child:only-child:first-child选择器。我不太了解你提出具体要求的要求,但我认为这些是你最好的选择。

至于身体的高度至少是页面的高度,你应该看看CSS viewport units。这应该让你做你想做的事。

答案 4 :(得分:0)

抱歉太快了,最低身高不是一个选项。对不起。

您可以将部分的最小高度更改为100 /部分数的百分比:

  html, body {
    height: 100%;
    margin: 0;
  }

  section {
    margin: 0;
    min-height: 33%;
  }

jsfiddle