Nov 23, 2011

Occupy the remaining height in CSS

Posted Nov 23, 2011

Today, I learned something new in CSS. The question is fairly simple: How do you occupy the rest of the height of a page?  Let's say you have a header with a height of 200px (the blue area above), and for the bottom part, you want the height to be flexible and fill-in the rest (red part). Same idea can be applied to widths.

Solution:
Use of absolute positioning. Specify the top style to be the height of your header and set bottom to 0.

Sample:

<!DOCTYPE html>
<html> <head> <title>Auto-expand body height</title> <style type="text/css"> body { height: 100%; margin: 0;
 position: relative;
}

html {
  height: 100%;
}

html * { 
  box-sizing: border-box;
-webkit-box-sizing: border-box; -moz-box-sizing: border-box; } </style> </head> <body> <div style="height: 200px; border: 1px solid blue;"> </div> <div style="border: 1px solid red; position: absolute; top: 200px; bottom: 0; width: 100%;"> </div> </body> </html>


[Updated June, 2014] Or if you want a fixed footer too:
<!DOCTYPE html>
<html>
<head>
<title>Auto Expand</title>
<style type="text/css">

body {
 height: 100%;
 margin: 0;
 min-height: 450px;
 position: relative;
}

html {
  height: 100%;
}

html * { 
  box-sizing: border-box;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
}

</style>
</head>
<body>
  <div style="height: 200px; border: 1px solid blue;">
  </div>
  <div style="border: 1px solid red; position: absolute; top: 200px; bottom: 100px; width: 100%;">
  </div>
<div style="height: 100px; border: 1px solid green; position: absolute; bottom: 0; width: 100%;">
  </div>
</body>
</html>

6 comments:

  1. These are great tips. I've been looking for a solution to my cramped layout for awhile now. Thanks for this!

    calgary web design

    ReplyDelete
  2. What about a header/body/footer design? Is it possible using a similar trick?

    ReplyDelete
  3. It should be possible. I'll research about it and update you. Thank you for visiting!

    ReplyDelete
  4. Борис ТеохаровOctober 18, 2013 at 6:50 AM

    What about a flexible width header (not fixed as in your example)?

    ReplyDelete
  5. This is quite clever. :D

    I'm still disappointed that W3 forces people to hack CSS to be used for layout, rather than creating a layout standard that for example lets me set height=x%-of-remaining or some sort of excellent grid based layout engine like those used for Android/iOS apps. The web is more than documents, now.

    It would be nice of them to implement an extension-type interface across IE, FF and CR so that the community could put together a layout module themselves; it takes too long for browser standard procedures now, they're like an aging legal system.

    ReplyDelete