简体   繁体   中英

Stack div elements in css vertically (with dynamic height)

I'm trying for hours now to get the following working:

I'd like to have three divs in an container div.

  1. They need to be stacked vertically (topDiv, middleDiv, bottomDiv)
  2. the topDiv should be 20px tall (fixed)
  3. the middleDiv should take the rest of space left (like * in a table or \\vfill in LaTeX)
  4. the bottomDiv should be 50px tall (fixed)

that does not sound so hard does it? I just can't figure it out!

thanks for your help.

something like this may work for you:

http://jsfiddle.net/nCrEc/1/

edit:

this version scales with the browser window http://jsfiddle.net/nCrEc/2/

html:

<div class="con">
    <div class="top"></div>
    <div class="middle"></div>
    <div class="bottom"></div>
</div>

css:

.con{width:200px; top:0;bottom:0;left:0; position:absolute;background:#ff0;}

.top{width:200px;height:20px;position:absolute;top:0;left:0;background:#f60;}

.bottom{width:200px;height:50px;position:absolute;bottom:0;left:0;background:#f60;}
.middle{width:200px;min-height:1px; position:absolute;bottom:50px;top:20px;left:0;background:#06f;}

It's easy with Flexbox but it is still being developed and only really works in Chrome at the moment.

Otherwise, you can use * {box-sizing: border-box;} to make your life easier. There is even an IE6-7 polyfill if supporting old browsers is important to you.

Here is an example .

*{-moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; margin:0; padding:0;}
html,body{width:100%; height:100%;}
div{width:100%; background:salmon;}
.middle {background:lightblue; height:100%; padding:100px 0;}
.top, .bottom {height:100px; position: absolute; left:0;}
.top {top:0; }
.bottom {bottom: 0;}

I did something very similar on this website:

http://www.probusllandudno.org.uk/

click the dinners 2012 link (and, if using FF web developer, u can use view generated source)

The main points are putting the divs in order in the doc, assigning fixed width (in my case) or width=100%, top and botom divs have fixed height see the css

ADDENDUM

Another response offers a sophisticated solution that covers issues around most specifically padding.. You haven't specified how your content might influence the solution. My web page is just centered text

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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