简体   繁体   English

让一个div填充剩余屏幕空间的高度

[英]Make a div fill the height of the remaining screen space

I am working on a web application where I want the content to fill the height of the entire screen.我正在开发一个 web 应用程序,我希望内容填满整个屏幕的高度。

The page has a header, which contains a logo, and account information.该页面有一个 header,其中包含徽标和帐户信息。 This could be an arbitrary height.这可以是任意高度。 I want the content div to fill the rest of the page to the bottom.我想让内容div把页面的rest填到底部。

I have a header div and a content div .我有一个 header div和一个内容div At the moment I am using a table for the layout like so:目前我正在使用表格进行布局,如下所示:

CSS and HTML CSS 和 HTML

 #page { height: 100%; width: 100% } #tdcontent { height: 100%; } #content { overflow: auto; /* or overflow: hidden; */ }
 <table id="page"> <tr> <td id="tdheader"> <div id="header">...</div> </td> </tr> <tr> <td id="tdcontent"> <div id="content">...</div> </td> </tr> </table>

The entire height of the page is filled, and no scrolling is required.页面的整个高度被填满,不需要滚动。

For anything inside the content div, setting top: 0;对于内容 div 内的任何内容,设置top: 0; will put it right underneath the header. Sometimes the content will be a real table, with its height set to 100%.会将其放在 header 的正下方。有时内容将是一个真实的表格,其高度设置为 100%。 Putting header inside content will not allow this to work.header放入content中将无法正常工作。

Is there a way to achieve the same effect without using the table ?有没有办法在不使用table的情况下达到同样的效果?

Update:更新:

Elements inside the content div will have heights set to percentages as well.内容div内的元素也将高度设置为百分比。 So something at 100% inside the div will fill it to the bottom.因此, div中 100% 的内容会将其填充到底部。 As will two elements at 50%.两个元素也将达到 50%。

Update 2:更新 2:

For instance, if the header takes up 20% of the screen's height, a table specified at 50% inside #content would take up 40% of the screen space.例如,如果 header 占据屏幕高度的 20%,则#content中指定为 50% 的表格将占据屏幕空间的 40%。 So far, wrapping the entire thing in a table is the only thing that works.到目前为止,将整个内容包装在一个表中是唯一可行的方法。

2015 update: the flexbox approach 2015 年更新:flexbox 方法

There are two other answers briefly mentioning flexbox ;还有另外两个答案简要提到了 flexbox however, that was more than two years ago, and they don't provide any examples.但是,那是两年多以前的事了,他们没有提供任何示例。 The specification for flexbox has definitely settled now. flexbox 的规范现在已经确定了。

Note: Though CSS Flexible Boxes Layout specification is at the Candidate Recommendation stage, not all browsers have implemented it.注意:虽然 CSS 灵活框布局规范处于候选推荐阶段,但并非所有浏览器都实现了它。 WebKit implementation must be prefixed with -webkit-; WebKit 实现必须以 -webkit- 为前缀; Internet Explorer implements an old version of the spec, prefixed with -ms-; Internet Explorer 实现了旧版本的规范,前缀为 -ms-; Opera 12.10 implements the latest version of the spec, unprefixed. Opera 12.10 实现了最新版本的规范,没有前缀。 See the compatibility table on each property for an up-to-date compatibility status.有关最新的兼容性状态,请参阅每个属性的兼容性表。

(taken from https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes ) (取自https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes

All major browsers and IE11+ support Flexbox.所有主流浏览器和 IE11+ 都支持 Flexbox。 For IE 10 or older, you can use the FlexieJS shim.对于 IE 10 或更早版本,您可以使用 FlexieJS shim。

To check current support you can also see here: http://caniuse.com/#feat=flexbox要检查当前支持,您还可以在此处查看:http: //caniuse.com/#feat=flexbox

Working example工作示例

With flexbox you can easily switch between any of your rows or columns either having fixed dimensions, content-sized dimensions or remaining-space dimensions.使用 flexbox,您可以轻松地在具有固定尺寸、内容尺寸尺寸或剩余空间尺寸的任何行或列之间切换。 In my example I have set the header to snap to its content (as per the OPs question), I've added a footer to show how to add a fixed-height region and then set the content area to fill up the remaining space.在我的示例中,我已将页眉设置为对齐其内容(根据 OPs 问题),我添加了一个页脚以显示如何添加固定高度区域,然后设置内容区域以填充剩余空间。

 html, body { height: 100%; margin: 0; } .box { display: flex; flex-flow: column; height: 100%; } .box .row { border: 1px dotted grey; } .box .row.header { flex: 0 1 auto; /* The above is shorthand for: flex-grow: 0, flex-shrink: 1, flex-basis: auto */ } .box .row.content { flex: 1 1 auto; } .box .row.footer { flex: 0 1 40px; }
 <!-- Obviously, you could use HTML5 tags like `header`, `footer` and `section` --> <div class="box"> <div class="row header"> <p><b>header</b> <br /> <br />(sized to content)</p> </div> <div class="row content"> <p> <b>content</b> (fills remaining space) </p> </div> <div class="row footer"> <p><b>footer</b> (fixed height)</p> </div> </div>

In the CSS above, the flex property shorthands the flex-grow , flex-shrink , and flex-basis properties to establish the flexibility of the flex items.在上面的 CSS 中, flex属性是flex-growflex-shrinkflex-basis属性的简写,以建立弹性项目的灵活性。 Mozilla has a good introduction to the flexible boxes model . Mozilla 对灵活盒子模型有很好的介绍

There really isn't a sound, cross-browser way to do this in CSS.在 CSS 中确实没有一种可靠的、跨浏览器的方式来做到这一点。 Assuming your layout has complexities, you need to use JavaScript to set the element's height.假设您的布局很复杂,您需要使用 JavaScript 来设置元素的高度。 The essence of what you need to do is:您需要做的事情的本质是:

Element Height = Viewport height - element.offset.top - desired bottom margin

Once you can get this value and set the element's height, you need to attach event handlers to both the window onload and onresize so that you can fire your resize function.一旦您可以获取此值并设置元素的高度,您需要将事件处理程序附加到窗口 onload 和 onresize 以便您可以触发您的调整大小功能。

Also, assuming your content could be larger than the viewport, you will need to set overflow-y to scroll.此外,假设您的内容可能大于视口,您将需要设置 overflow-y 来滚动。

The original post is more than 3 years ago.原来的帖子是3年前的。 I guess many people who come to this post like me are looking for an app-like layout solution, say a somehow fixed header, footer, and full height content taking up the rest screen.我想很多像我一样来看这篇文章的人都在寻找类似应用程序的布局解决方案,比如以某种方式固定的页眉、页脚和占据其余屏幕的全高内容。 If so, this post may help, it works on IE7+, etc.如果是这样,这篇文章可能会有所帮助,它适用于 IE7+ 等。

http://blog.stevensanderson.com/2011/10/05/full-height-app-layouts-a-css-trick-to-make-it-easier/ http://blog.stevensanderson.com/2011/10/05/full-height-app-layouts-a-css-trick-to-make-it-easier/

And here are some snippets from that post:以下是该帖子的一些片段:

 @media screen { /* start of screen rules. */ /* Generic pane rules */ body { margin: 0 } .row, .col { overflow: hidden; position: absolute; } .row { left: 0; right: 0; } .col { top: 0; bottom: 0; } .scroll-x { overflow-x: auto; } .scroll-y { overflow-y: auto; } .header.row { height: 75px; top: 0; } .body.row { top: 75px; bottom: 50px; } .footer.row { height: 50px; bottom: 0; } /* end of screen rules. */ }
 <div class="header row" style="background:yellow;"> <h2>My header</h2> </div> <div class="body row scroll-y" style="background:lightblue;"> <p>The body</p> </div> <div class="footer row" style="background:#e9e9e9;"> My footer </div>

Instead of using tables in the markup, you could use CSS tables.您可以使用 CSS 表格,而不是在标记中使用表格。

Markup标记

<body>    
    <div>hello </div>
    <div>there</div>
</body>

(Relevant) CSS (相关)CSS

body
{
    display:table;
    width:100%;
}
div
{
    display:table-row;
}
div+ div
{
    height:100%;  
}

FIDDLE1 and FIDDLE2 FIDDLE1FIDDLE2

Some advantages of this method are:这种方法的一些优点是:

1) Less markup 1) 少加价

2) Markup is more semantic than tables, because this is not tabular data. 2) 标记比表格更具语义,因为这不是表格数据。

3) Browser support is very good : IE8+, All modern browsers and mobile devices ( caniuse ) 3)浏览器支持非常好:IE8+,所有现代浏览器和移动设备( caniuse


Just for completeness, here are the equivalent Html elements to css properties for the The CSS table model 为了完整起见,这里是与CSS 表格模型的CSS 属性等效的 Html 元素

table { display: table } tr { display: table-row } thead { display: table-header-group } tbody { display: table-row-group } tfoot { display: table-footer-group } col { display: table-column } colgroup { display: table-column-group } td, th { display: table-cell } caption { display: table-caption }

CSS only Approach (If height is known/fixed)仅 CSS 方法(如果高度已知/固定)

When you want the middle element to span across entire page vertically, you can use calc() which is introduced in CSS3.当您希望中间元素垂直跨越整个页面时,可以使用 CSS3 中引入的calc()

Assuming we have a fixed height header and footer elements and we want the section tag to take entire available vertical height...假设我们有一个固定高度headerfooter元素,并且我们希望section标签占据整个可用的垂直高度......

Demo演示

Assumed markup and your CSS should be假定的标记和你的 CSS 应该是

 html, body { height: 100%; } header { height: 100px; background: grey; } section { height: calc(100% - (100px + 150px)); /* Adding 100px of header and 150px of footer */ background: tomato; } footer { height: 150px; background-color: blue; }
 <header>100px</header> <section>Expand me for remaining space</section> <footer>150px</footer>

So here, what am doing is, adding up the height of elements and than deducting from 100% using calc() function.所以在这里,我正在做的是,将元素的高度相加,然后使用calc()函数从100%中扣除。

Just make sure that you use height: 100%;只要确保你使用height: 100%; for the parent elements.对于父元素。

Used: height: calc(100vh - 110px);使用: height: calc(100vh - 110px);

code:代码:

 .header { height: 60px; top: 0; background-color: green} .body { height: calc(100vh - 110px); /*50+60*/ background-color: gray; } .footer { height: 50px; bottom: 0; }
 <div class="header"> <h2>My header</h2> </div> <div class="body"> <p>The body</p> </div> <div class="footer"> My footer </div>

A simple solution, using flexbox:一个简单的解决方案,使用 flexbox:

 html, body { height: 100%; } body { display: flex; flex-direction: column; } .content { flex-grow: 1; }
 <body> <div>header</div> <div class="content"></div> </body>

Codepen sample Codepen 示例

An alternate solution, with a div centered within the content div另一种解决方案,div 以内容 div 为中心

How about you simply use vh which stands for view height in CSS ...你如何简单地使用vh ,它代表CSS中的view height ......

Look at the code snippet I created for you below and run it:查看我在下面为您创建的代码片段并运行它:

 body { padding: 0; margin: 0; } .full-height { width: 100px; height: 100vh; background: red; }
 <div class="full-height"> </div>

Also, look at the image below which I created for you:另外,请看下面我为您创建的图像:

使一个 div 填充剩余屏幕空间的高度

None of the solutions posted work when you need the bottom div to scroll when the content is too tall.当内容太高时需要底部 div 滚动时,发布的解决方案都不起作用。 Here's a solution that works in that case:这是在这种情况下有效的解决方案:

 .table { display: table; } .table-row { display: table-row; } .table-cell { display: table-cell; } .container { width: 400px; height: 300px; } .header { background: cyan; } .body { background: yellow; height: 100%; } .body-content-outer-wrapper { height: 100%; } .body-content-inner-wrapper { height: 100%; position: relative; overflow: auto; } .body-content { position: absolute; top: 0; bottom: 0; left: 0; right: 0; }
 <div class="table container"> <div class="table-row header"> <div>This is the header whose height is unknown</div> <div>This is the header whose height is unknown</div> <div>This is the header whose height is unknown</div> </div> <div class="table-row body"> <div class="table-cell body-content-outer-wrapper"> <div class="body-content-inner-wrapper"> <div class="body-content"> <div>This is the scrollable content whose height is unknown</div> <div>This is the scrollable content whose height is unknown</div> <div>This is the scrollable content whose height is unknown</div> <div>This is the scrollable content whose height is unknown</div> <div>This is the scrollable content whose height is unknown</div> <div>This is the scrollable content whose height is unknown</div> <div>This is the scrollable content whose height is unknown</div> <div>This is the scrollable content whose height is unknown</div> <div>This is the scrollable content whose height is unknown</div> <div>This is the scrollable content whose height is unknown</div> <div>This is the scrollable content whose height is unknown</div> <div>This is the scrollable content whose height is unknown</div> <div>This is the scrollable content whose height is unknown</div> <div>This is the scrollable content whose height is unknown</div> <div>This is the scrollable content whose height is unknown</div> <div>This is the scrollable content whose height is unknown</div> <div>This is the scrollable content whose height is unknown</div> <div>This is the scrollable content whose height is unknown</div> </div> </div> </div> </div> </div>

Original source: Filling the Remaining Height of a Container While Handling Overflow in CSS 原始来源:在 CSS 中处理溢出时填充容器的剩余高度

JSFiddle live preview JSFiddle 实时预览

CSS3 Simple Way CSS3 简单方式

height: calc(100% - 10px); // 10px is height of your first div...

all major browsers these days support it, so go ahead if you don't have requirement to support vintage browsers.现在所有主流浏览器都支持它,所以如果您不需要支持老式浏览器,请继续。

It could be done purely by CSS using vh :它可以完全由CSS使用vh来完成:

#page {
    display:block; 
    width:100%; 
    height:95vh !important; 
    overflow:hidden;
}

#tdcontent {
    float:left; 
    width:100%; 
    display:block;
}

#content {      
    float:left; 
    width:100%; 
    height:100%; 
    display:block; 
    overflow:scroll;
}

and the HTMLHTML

<div id="page">

   <div id="tdcontent"></div>
   <div id="content"></div>

</div>

I checked it, It works in all major browsers: Chrome , IE , and FireFox我检查了一下,它适用于所有主流浏览器: ChromeIEFireFox

Disclaimer: The accepted answer gives the idea of the solution, but I'm finding it a bit bloated with an unnecessary wrapper and css rules.免责声明:接受的答案给出了解决方案的想法,但我发现它有点臃肿,带有不必要的包装器和 css 规则。 Below is a solution with very few css rules.下面是一个 CSS 规则很少的解决方案。

HTML 5 HTML 5

<body>
    <header>Header with an arbitrary height</header>
    <main>
        This container will grow so as to take the remaining height
    </main>
</body>

CSS CSS

body {
  display: flex;
  flex-direction: column;
  min-height: 100vh;       /* body takes whole viewport's height */
}

main {
  flex: 1;                 /* this will make the container take the free space */
}

Solution above uses viewport units and flexbox , and is therefore IE10+, providing you use the old syntax for IE10.上面的解决方案使用viewport unitsflexbox ,因此是 IE10+,提供您使用 IE10 的旧语法。

Codepen to play with: link to codepen要玩的 Codepen: codepen 的链接

Or this one, for those needing the main container to be scrollable in case of overflowing content: link to codepen或者这个,对于那些需要主容器在内容溢出的情况下可滚动的人: link to codepen

I've been searching for an answer for this as well.我也一直在寻找这个问题的答案。 If you are fortunate enough to be able to target IE8 and up, you can use display:table and related values to get the rendering rules of tables with block-level elements including div.如果您有幸能够针对 IE8 及更高版本,您可以使用display:table和相关值来获取包含 div 在内的具有块级元素的表格的呈现规则。

If you are even luckier and your users are using top-tier browsers (for example, if this is an intranet app on computers you control, like my latest project is), you can use the new Flexible Box Layout in CSS3!如果您更幸运,并且您的用户正在使用顶级浏览器(例如,如果这是您控制的计算机上的 Intranet 应用程序,就像我的最新项目一样),您可以使用 CSS3 中新的灵活框布局

What worked for me (with a div within another div and I assume in all other circumstances) is to set the bottom padding to 100%.对我有用的(在另一个 div 中有一个 div,我假设在所有其他情况下)是将底部填充设置为 100%。 That is, add this to your css / stylesheet:也就是说,将其添加到您的 css / 样式表中:

padding-bottom: 100%;

There's a ton of answers now, but I found using height: 100vh;现在有很多答案,但我发现使用height: 100vh; to work on the div element that needs to fill up the entire vertical space available.处理需要填满整个可用垂直空间的 div 元素。

In this way, I do not need to play around with display or positioning.这样,我就不需要玩弄显示或定位了。 This came in handy when using Bootstrap to make a dashboard wherein I had a sidebar and a main.这在使用 Bootstrap 制作仪表板时派上了用场,其中我有一个侧边栏和一个主栏。 I wanted the main to stretch and fill the entire vertical space so that I could apply a background colour.我希望主体能够拉伸并填充整个垂直空间,以便我可以应用背景颜色。

div {
    height: 100vh;
}

Supports IE9 and up: click to see the link支持IE9及以上:点击查看链接

In Bootstrap:在引导程序中:

CSS Styles: CSS 样式:

html, body {
    height: 100%;
}

1) Just fill the height of the remaining screen space: 1)只需填充剩余屏幕空间的高度:

<body class="d-flex flex-column">
  <div class="d-flex flex-column flex-grow-1">

    <header>Header</header>
    <div>Content</div>
    <footer class="mt-auto">Footer</footer>

  </div>
</body>

![在此处输入图像描述


2) fill the height of the remaining screen space and aligning content to the middle of the parent element: 2)填充剩余屏幕空间的高度并将内容对齐到父元素的中间:

<body class="d-flex flex-column">
  <div class="d-flex flex-column flex-grow-1">

    <header>Header</header>
    <div class="d-flex flex-column flex-grow-1 justify-content-center">Content</div>
    <footer class="mt-auto">Footer</footer>

  </div>
</body>

![在此处输入图像描述

If you can deal with not supporting old browsers (that is, MSIE 9 or older), you can do this with Flexible Box Layout Module which is already W3C CR.如果您可以处理不支持旧浏览器(即 MSIE 9 或更早版本)的问题,您可以使用已经是 W3C CR 的灵活框布局模块来做到这一点。 That module allows other nice tricks, too, such as re-ordering content.该模块还允许其他一些不错的技巧,例如重新排序内容。

Unfortunately, MSIE 9 or lesser do not support this and you have to use vendor prefix for the CSS property for every browser other than Firefox.不幸的是,MSIE 9 或更低版本不支持此功能,您必须为除 Firefox 之外的所有浏览器的 CSS 属性使用供应商前缀。 Hopefully other vendors drop the prefix soon, too.希望其他供应商也能尽快放弃该前缀。

An another choice would be CSS Grid Layout but that has even less support from stable versions of browsers.另一种选择是CSS 网格布局,但稳定版本的浏览器对它的支持更少。 In practice, only MSIE 10 supports this.实际上,只有 MSIE 10 支持这一点。

Update year 2020 : All modern browsers support both display: flex and display: grid . 2020 年更新:所有现代浏览器都支持display: flexdisplay: grid The only one missing is support for subgrid which in only supported by Firefox.唯一缺少的是对仅 Firefox 支持的subgrid的支持。 Note that MSIE does not support either by the spec but if you're willing to add MSIE specific CSS hacks, it can be made to behave.请注意,规范不支持 MSIE,但如果您愿意添加特定于 MSIE 的 CSS hack,则可以使其正常运行。 I would suggest simply ignoring MSIE because even Microsoft says it should not be used anymore.我建议直接忽略 MSIE,因为即使微软也表示不应该再使用它。 Microsoft Edge supports these features just fine (except for subgrid support since is shares the Blink rendering engine with Chrome). Microsoft Edge 很好地支持这些功能(除了子网格支持,因为它与 Chrome 共享 Blink 渲染引擎)。

Example using display: grid :使用display: grid

 html, body { min-height: 100vh; padding: 0; margin: 0; } body { display: grid; grid: "myheader" auto "mymain" minmax(0,1fr) "myfooter" auto / minmax(10rem, 90rem); } header { grid-area: myheader; background: yellow; } main { grid-area: mymain; background: pink; align-self: center /* or stretch + display: flex; + flex-direction: column; + justify-content: center; */ } footer { grid-area: myfooter; background: cyan; }
 <header>Header content</header> <main>Main content which should be centered and the content length may change. <details><summary>Collapsible content</summary> <p>Here's some text to cause more vertical space to be used.</p> <p>Here's some text to cause more vertical space to be used (2).</p> <p>Here's some text to cause more vertical space to be used (3).</p> <p>Here's some text to cause more vertical space to be used (4).</p> <p>Here's some text to cause more vertical space to be used (5).</p> </details> </main> <footer>Footer content</footer>

Example using display: flex :使用display: flex

 html, body { min-height: 100vh; padding: 0; margin: 0; } body { display: flex; } main { background: pink; align-self: center; }
 <main>Main content which should be centered and the content length may change. <details><summary>Collapsible content</summary> <p>Here's some text to cause more vertical space to be used.</p> <p>Here's some text to cause more vertical space to be used (2).</p> <p>Here's some text to cause more vertical space to be used (3).</p> <p>Here's some text to cause more vertical space to be used (4).</p> <p>Here's some text to cause more vertical space to be used (5).</p> </details> </main>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Test</title>
<style type="text/css">
body
,html
{
    height: 100%;
    margin: 0;
    padding: 0;
    color: #FFF;
}

#header
{
    float: left;
    width: 100%;
    background: red;
}

#content
{
    height: 100%;
    overflow: auto;
    background: blue;
}

</style>
</head>
<body>

    <div id="content">
        <div id="header">
                Header
                <p>Header stuff</p>
        </div>
            Content
            <p>Content stuff</p>
    </div>

</body>
</html>

In all sane browsers, you can put the "header" div before the content, as a sibling, and the same CSS will work.在所有健全的浏览器中,您可以将“标题” div 作为同级放在内容之前,并且相同的 CSS 将起作用。 However, IE7- does not interpret the height correctly if the float is 100% in that case, so the header needs to be IN the content, as above.但是,如果在这种情况下浮动为 100%,则 IE7- 不会正确解释高度,因此标题需要在内容中,如上所述。 The overflow: auto will cause double scroll bars on IE (which always has the viewport scrollbar visible, but disabled), but without it, the content will clip if it overflows. overflow: auto 将导致 IE 上的双滚动条(它始终使视口滚动条可见,但已禁用),但没有它,如果内容溢出,内容将被剪辑。

CSS Grid Solution CSS 网格解决方案

Just defining the body with display:grid and the grid-template-rows using auto and the fr value property.只需使用display:grid和使用autofr value 属性的grid-template-rows定义body

 * { margin: 0; padding: 0; } html { height: 100%; } body { min-height: 100%; display: grid; grid-template-rows: auto 1fr auto; } header { padding: 1em; background: pink; } main { padding: 1em; background: lightblue; } footer { padding: 2em; background: lightgreen; } main:hover { height: 2000px; /* demos expansion of center element */ }
 <header>HEADER</header> <main>MAIN</main> <footer>FOOTER</footer>

A Complete Guide to Grids @ CSS-Tricks.com 网格完整指南 @ CSS-Tricks.com

This is my own minimal version of Pebbl's solution.这是我自己的 Pebbl 解决方案的最小版本。 Took forever to find the trick to get it to work in IE11.花了很长时间才找到让它在 IE11 中工作的技巧。 (Also tested in Chrome, Firefox, Edge, and Safari.) (也在 Chrome、Firefox、Edge 和 Safari 中进行了测试。)

 html { height: 100%; } body { height: 100%; margin: 0; } section { display: flex; flex-direction: column; height: 100%; } div:first-child { background: gold; } div:last-child { background: plum; flex-grow: 1; }
 <body> <section> <div>FIT</div> <div>GROW</div> </section> </body>

I wresteled with this for a while and ended up with the following:我为此挣扎了一段时间,最终得到以下结果:

Since it is easy to make the content DIV the same height as the parent but apparently difficult to make it the parent height minus the header height I decided to make content div full height but position it absolutely in the top left corner and then define a padding for the top which has the height of the header.由于很容易使内容 DIV 与父级高度相同,但显然很难使其父级高度减去标题高度,我决定将内容 div 设为全高,但将其绝对定位在左上角,然后定义填充对于具有标题高度的顶部。 This way the content displays neatly under the header and fills the whole remaining space:这样,内容会整齐地显示在标题下方并填充整个剩余空间:

body {
    padding: 0;
    margin: 0;
    height: 100%;
    overflow: hidden;
}

#header {
    position: absolute;
    top: 0;
    left: 0;
    height: 50px;
}

#content {
    position: absolute;
    top: 0;
    left: 0;
    padding-top: 50px;
    height: 100%;
}

Why not just like this?为什么不只是这样?

html, body {
    height: 100%;
}

#containerInput {
    background-image: url('../img/edit_bg.jpg');
    height: 40%;
}

#containerControl {
    background-image: url('../img/control_bg.jpg');
    height: 60%;
}

Giving you html and body (in that order) a height and then just give your elements a height?给你 html 和 body(按这个顺序)一个高度,然后给你的元素一个高度?

Works for me为我工作

You can actually use display: table to split the area into two elements (header and content), where the header can vary in height and the content fills the remaining space.您实际上可以使用display: table将区域拆分为两个元素(标题和内容),其中标题的高度可以不同,而内容会填充剩余空间。 This works with the whole page, as well as when the area is simply the content of another element positioned with position set to relative , absolute or fixed .这适用于整个页面,以及当区域只是另一个元素的内容时, position设置为relativeabsolutefixed It will work as long as the parent element has a non-zero height.只要父元素的高度不为零,它就会起作用。

See this fiddle and also the code below:请参阅此小提琴以及以下代码:

CSS: CSS:

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

p {
    margin: 0;
    padding: 0;
}

.additional-padding {
    height: 50px;
    background-color: #DE9;
}

.as-table {
    display: table;
    height: 100%;
    width: 100%;
}

.as-table-row {
    display: table-row;
    height: 100%;
}

#content {
    width: 100%;
    height: 100%;
    background-color: #33DD44;
}

HTML: HTML:

<div class="as-table">
    <div id="header">
        <p>This header can vary in height, it also doesn't have to be displayed as table-row. It will simply take the necessary space and the rest below will be taken by the second div which is displayed as table-row. Now adding some copy to artificially expand the header.</p>
        <div class="additional-padding"></div>
    </div>
    <div class="as-table-row">
        <div id="content">
            <p>This is the actual content that takes the rest of the available space.</p>
        </div>
    </div>
</div>
 style="height:100vh"

solved the problem for me.为我解决了这个问题。 In my case I applied this to the required div就我而言,我将此应用于所需的 div

For mobile app i use only VH and VW对于移动应用程序,我只使用 VH 和 VW

<div class="container">
    <div class="title">Title</div>
    <div class="content">Content</div>
    <div class="footer">Footer</div>
</div>
.container {
    width: 100vw;
    height: 100vh;
    font-size: 5vh;
}
    
.title {
    height: 20vh;
    background-color: red;
}
    
.content {
    height: 60vh;
    background: blue;
}
    
.footer {
    height: 20vh;
    background: green;
}

Demo - https://jsfiddle.net/u763ck92/演示 - https://jsfiddle.net/u763ck92/

Vincent, I'll answer again using your new requirements.文森特,我会用你的新要求再次回答。 Since you don't care about the content being hidden if it's too long, you don't need to float the header.由于您不关心内容是否太长而被隐藏,因此您不需要浮动标题。 Just put overflow hidden on the html and body tags, and set #content height to 100%.只需将溢出隐藏在 html 和 body 标签上,并将#content高度设置为 100%。 The content will always be longer than the viewport by the height of the header, but it'll be hidden and won't cause scrollbars.内容将始终比视口长标题的高度,但它会被隐藏并且不会导致滚动条。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>Test</title>
    <style type="text/css">
    body, html {
      height: 100%;
      margin: 0;
      padding: 0;
      overflow: hidden;
      color: #FFF;
    }
    p {
      margin: 0;
    }

    #header {
      background: red;
    }

    #content {
      position: relative;
      height: 100%;
      background: blue;
    }

    #content #positioned {
      position: absolute;
      top: 0;
      right: 0;
    }
  </style>
</head>

<body>
  <div id="header">
    Header
    <p>Header stuff</p>
  </div>

  <div id="content">
    Content
    <p>Content stuff</p>
    <div id="positioned">Positioned Content</div>
  </div>

</body>
</html>

Try this尝试这个

var sizeFooter = function(){
    $(".webfooter")
        .css("padding-bottom", "0px")
        .css("padding-bottom", $(window).height() - $("body").height())
}
$(window).resize(sizeFooter);

Spinning off the idea of Mr. Alien...分拆外星人先生的想法...

This seems a cleaner solution than the popular flex box one for CSS3 enabled browsers.对于支持 CSS3 的浏览器,这似乎比流行的 flex box 更简洁。

Simply use min-height(instead of height) with calc() to the content block.只需将 min-height(而不是 height)与 calc() 一起用于内容块。

The calc() starts with 100% and subtracts heights of headers and footers (need to include padding values) calc() 从 100% 开始并减去页眉和页脚的高度(需要包括填充值)

Using "min-height" instead of "height" is particularly useful so it can work with javascript rendered content and JS frameworks like Angular2.使用“min-height”而不是“height”特别有用,因此它可以与 javascript 呈现的内容和 Angular2 等 JS 框架一起使用。 Otherwise, the calculation will not push the footer to the bottom of the page once the javascript rendered content is visible.否则,一旦 javascript 呈现的内容可见,计算将不会将页脚推到页面底部。

Here is a simple example of a header and footer using 50px height and 20px padding for both.这是一个使用 50px 高度和 20px 填充的页眉和页脚的简单示例。

Html: html:

<body>
    <header></header>
    <div class="content"></div>
    <footer></footer>
</body>

Css: CSS:

.content {
    min-height: calc(100% - (50px + 20px + 20px + 50px + 20px + 20px));
}

Of course, the math can be simplified but you get the idea...当然,数学可以简化,但你明白了......

I had the same problem but I could not make work the solution with flexboxes above.我遇到了同样的问题,但我无法使用上面的 flexbox 解决方案。 So I created my own template, that includes:所以我创建了自己的模板,其中包括:

  • a header with a fixed size element具有固定大小元素的标题
  • a footer页脚
  • a side bar with a scrollbar that occupies the remaining height带有占据剩余高度的滚动条的侧边栏
  • content内容

I used flexboxes but in a more simple way, using only properties display: flex and flex-direction: row|column :我使用了 flexbox,但以更简单的方式,仅使用属性display: flexflex-direction: row|column

I do use angular and I want my component sizes to be 100% of their parent element.我确实使用 angular 并且我希望我的组件大小是其父元素的 100%。

The key is to set the size (in percents) for all parents inorder to limit their size.关键是为所有父母设置大小(以百分比为单位),以限制他们的大小。 In the following example myapp height has 100% of the viewport.在以下示例中,myapp 高度具有 100% 的视口。

The main component has 90% of the viewport, because header and footer have 5%.主要组件有 90% 的视口,因为页眉和页脚有 5%。

I posted my template here: https://jsfiddle.net/abreneliere/mrjh6y2e/3我在这里发布了我的模板: https ://jsfiddle.net/abreneliere/mrjh6y2e/3

       body{
        margin: 0;
        color: white;
        height: 100%;
    }
    div#myapp
    {
        display: flex;
        flex-direction: column;
        background-color: red; /* <-- painful color for your eyes ! */
        height: 100%; /* <-- if you remove this line, myapp has no limited height */
    }
    div#main /* parent div for sidebar and content */
    {
        display: flex;
        width: 100%;
        height: 90%; 
    }
    div#header {
        background-color: #333;
        height: 5%;
    }
    div#footer {
        background-color: #222;
        height: 5%;
    }
    div#sidebar {
        background-color: #666;
        width: 20%;
        overflow-y: auto;
     }
    div#content {
        background-color: #888;
        width: 80%;
        overflow-y: auto;
    }
    div.fized_size_element {
        background-color: #AAA;
        display: block;
        width: 100px;
        height: 50px;
        margin: 5px;
    }

Html: html:

<body>
<div id="myapp">
    <div id="header">
        HEADER
        <div class="fized_size_element"></div>

    </div>
    <div id="main">
        <div id="sidebar">
            SIDEBAR
            <div class="fized_size_element"></div>
            <div class="fized_size_element"></div>
            <div class="fized_size_element"></div>
            <div class="fized_size_element"></div>
            <div class="fized_size_element"></div>
            <div class="fized_size_element"></div>
            <div class="fized_size_element"></div>
            <div class="fized_size_element"></div>
        </div>
        <div id="content">
            CONTENT
        </div>
    </div>
    <div id="footer">
        FOOTER
    </div>
</div>
</body>

I found a quite simple solution, because for me it was just a design issue.我找到了一个非常简单的解决方案,因为对我来说这只是一个设计问题。 I wanted the rest of the Page not to be white below the red footer.我希望页面的其余部分在红色页脚下方不是白色的。 So i set the pages background color to red.所以我将页面背景颜色设置为红色。 And the contents backgroundcolor to white.并且内容背景颜色为白色。 With the contents height set to eg.内容高度设置为例如。 20em or 50% an almost empty page won't leave the whole page red. 20em 或 50% 几乎是空的页面不会使整个页面变红。

One more solution using CSS Grid使用CSS Grid 的另一种解决方案

Define grid定义网格

.root {
  display: grid;
  grid-template-rows: minmax(60px, auto) minmax(0, 100%);
}

First row(header): Min height can be set-up and max height will depend on content.第一行(标题):可以设置最小高度,最大高度取决于内容。 Second row(content) will try to fit free space that left after header.第二行(内容)将尝试适应标题后剩余的可用空间。

The advantage of this approach is content can be scrolled independently of header, so header is always at the top of the page这种方法的优点是内容可以独立于页眉滚动,因此页眉始终位于页面顶部

 body, html { margin: 0; height: 100%; } .root { display: grid; grid-template-rows: minmax(60px, auto) minmax(0, 100%); height: 100%; } .header { background-color: lightblue; } button { background-color: darkslateblue; color: white; padding: 10px 50px; margin: 10px 30px; border-radius: 15px; border: none; } .content { background-color: antiquewhite; overflow: auto; } .block { width: calc(100% - 20px); height: 120px; border: solid aquamarine; margin: 10px; }
 <div class="root"> <div class="header"> <button>click</button> <button>click</button> <button>click</button> <button>click</button> <button>click</button> </div> <div class="content"> <div class="block"></div> <div class="block"></div> <div class="block"></div> <div class="block"></div> <div class="block"></div> <div class="block"></div> <div class="block"></div> <div class="block"></div> </div> <div class="footer"></div> </div>

For me the easiest way to do this is by using Grid.对我来说,最简单的方法是使用 Grid。 But, I am looking for an easier approach.但是,我正在寻找一种更简单的方法。 Here is How I am doing it and it works.这是我如何做的并且它有效。 But, it becomes too much of pain if we have a lot of nested divs.但是,如果我们有很多嵌套的 div,那就太痛苦了。

 <div style={{
  display:grid,
  gridTemplateRows:'max-content 1fr',
}}>
   <div>
     Header
   </div>
   <div style={{height:'100%',minHeight:'0'}}>
     Content
   </div>
 </div>

A nice hack would be to set the css margin property to "auto".一个不错的技巧是将 css 边距属性设置为“自动”。 It will make the div take up all the remaining height & width.它将使 div 占据所有剩余的高度和宽度。

The downside is that it would be computed as margin and not the content.缺点是它将被计算为边距而不是内容。

See attached screenshots:请参阅随附的屏幕截图:

之前1 之前2

之后1

之后2

It's dynamic calc the remining screen space, better using Javascript. 动态计算刷新屏幕空间,使用Java更好。

You can use CSS-IN-JS technology, like below lib: 您可以使用CSS-IN-JS技术,如以下lib所示:

https://github.com/cssobj/cssobj https://github.com/cssobj/cssobj

DEMO: https://cssobj.github.io/cssobj-demo/ 演示: https : //cssobj.github.io/cssobj-demo/

Here is an answer that uses grids.这是一个使用网格的答案。

.the-container-div {
  display: grid;
  grid-template-columns: 1fr;
  grid-template-rows: auto min-content;
  height: 100vh;
}
.view-to-remain-small {
  grid-row: 2;
}

.view-to-be-stretched {
  grid-row: 1
}

Using pure CSS.使用纯 CSS。

Height of the 'content' DIV - That is placed between 'header' and 'footer' is found without doing any height calculation. “内容”DIV 的高度 - 位于“页眉”和“页脚”之间,无需进行任何高度计算。

please refer the below link.请参考以下链接。

https://stackblitz.com/edit/web-platform-njdf2p?file=index.html https://stackblitz.com/edit/web-platform-njdf2p?file=index.html

页眉-内容-页脚

Some of my components were loaded dynamically, and this caused me problems with setting the height of the navigation bar.我的一些组件是动态加载的,这导致我在设置导航栏高度时出现问题。

What I did was to use the ResizeObserver API .我所做的是使用ResizeObserver API

function observeMainResize(){
   const resizeObserver = new ResizeObserver(entries => {
      for (let entry of entries) {
         $("nav").height(Math.max($("main").height(),
                                  $("nav") .height()));
      }
   });
   resizeObserver.observe(document.querySelector('main'));
}

then:然后:

...
<body onload="observeMainResize()">
   <nav>...</nav>
   <main>...</main>
...

Consider setting all the 'position's to 'fixed', and then using {top:0;考虑将所有“位置”设置为“固定”,然后使用 {top:0; bottom:0;}底部:0;}

 <:DOCTYPE html> <html><head> <style> #B { position;fixed: width; 100%: height; 100%: background-color; orange: } #B1 { position;fixed: top;0: bottom; 0: width; 100%: background-color; cyan: } #B2 { position;fixed: bottom; 0: height; 35px: width; 100%: background; green; } }</style></head> <body> <div id="B1">B1</div> <div id="B2">B2</div> </body> </html>

Note that there is some overlapping, so be careful.请注意,有一些重叠,所以要小心。

If you want to vertically occupy the available space of a parent < div>, use absolute positioning instead.如果要垂直占用父 <div> 的可用空间,请改用绝对定位。

My method makes use of calc() function in CSS. It calculates the space remaining when an item of known size is on the page.我的方法在 CSS 中使用calc() function。它计算页面上已知大小的项目时剩余的空间。

 #fixed-size { height: 2rem; background-color: red; } #fill-remaining { background-color: blue; height: calc(100vh - 2rem); }
 <div> <div id="fixed-size">Known Size</div> <div id="fill-remaining">Fill Remaining</div> </div>

This help to me:这对我有帮助:

padding: 8px;
  display: table;
  width: calc(100% - PADDING_SIZEpx);
  height: calc(100% - TOOL_BARSIZEpx);

All you have to do if you're using display: flex on the parent div is to simply set height to stretch or fill like so如果您使用 display: flex 在父 div 上,您所要做的就是简单地将高度设置为拉伸或填充

.divName {
    height: stretch
}

it never worked for me in other way then with use of the JavaScript as NICCAI suggested in the very first answer. 就像在第一个答案中提到的NICCAI一样,使用JavaScript从未对我有任何帮助 I am using that approach to rescale the <div> with the Google Maps. 我正在使用这种方法通过Google Maps重新调整<div>比例。

Here is the full example how to do that (works in Safari/FireFox/IE/iPhone/Andorid (works with rotation)): 这是如何执行此操作的完整示例(在Safari / FireFox / IE / iPhone / Andorid中有效(可旋转)):

CSS 的CSS

body {
  height: 100%;
  margin: 0;
  padding: 0;
}

.header {
  height: 100px;
  background-color: red;
}

.content {
  height: 100%;
  background-color: green;
}

JS JS

function resize() {
  // Get elements and necessary element heights
  var contentDiv = document.getElementById("contentId");
  var headerDiv = document.getElementById("headerId");
  var headerHeight = headerDiv.offsetHeight;

  // Get view height
  var viewportHeight = document.getElementsByTagName('body')[0].clientHeight;

  // Compute the content height - we want to fill the whole remaining area
  // in browser window
  contentDiv.style.height = viewportHeight - headerHeight;
}

window.onload = resize;
window.onresize = resize;

HTML 的HTML

<body>
  <div class="header" id="headerId">Hello</div>
  <div class="content" id="contentId"></div>
</body>

height: calc(100% - 650px);高度:计算(100% - 650px); position: absolute; position:绝对;

If the only issue is height, just using divs seems to work:如果唯一的问题是高度,只使用 div 似乎工作:

<div id="header">header content</div>
<div id="content" style="height:100%">content content</div>

In a simple test, the width of header/content is different in your example and mine, but I'm not sure from your post if you're concerned about the width?在一个简单的测试中,您的示例和我的示例中标题/内容的宽度不同,但是我不确定您是否担心宽度?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM