How to make a div stretch its height between two other divs and center its content

余生颓废 提交于 2019-12-03 16:21:18

2018 update

use flexbox or css grid. Here is a flexbox example. Css grid could be even simpler, but support is pretty low still:

body, html { padding: 0; margin: 0; }
header { background: #faa; }
article { background: #afa; }
footer { background: #aaf; }

.page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  width: 100vw;
}

article {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
}
<div class="page">
  <header>header content</header>
  <article>main content</article>
  <footer>footer content</footer>
</div>

No need to use tables! Some simple css will do nicely.

DEMO: http://jsbin.com/azivip/2/edit

Html Markup:

<body>
  <div id="content">
    <div id="header">
      This is the header
    </div>
    <div id="inner">
      This is the body
     </div>
    <div id="footer">
      this is the footer
    </div>
  </div>
</body>

CSS:

body{
  height:100%;
  padding:0px;
  margin:0px;
}
    #content{
      position:relative;
      bottom:0px;
      width:100%;
      height:100%;
    }
        #header{
          position:relative;
          bottom:0px;
          width:100%;
          height:100px;    /* Edit for height of header*/
          background:#f00;
        }
        #inner{
          width:100%;
          text-align:center;
          position: absolute; 
          top: 50%;
          display: table-cell; 
          vertical-align: middle;
        }
        #footer{
          position:absolute;
          bottom:0px;
          width:100%;
          height:100px;   /* Edit for height of footer */
          background:#0f0;
        }

In order for #inner to stay centered vertically even with multi-line content, you'll need to use Javascript/jQuery. Below is an example script that "pulls up" #inner just the right amount to be centered.

var mrgntop = -Math.floor($("#inner").height() / 2);
$("#inner").css({"margin-top":mrgntop});

<table> is what you need to use in this case. The HTML will look like this, basically:

<table class = "wrapper">
    <tr><td class = "header">I'm the header.</td></tr>
    <tr><td valign = "middle" class = "content">Some content. Some content. More content. More content. Content is great. Content is a great thing to talk about when trying to insert random content to elaborate behavior. Content.</td></tr>
    <tr><td class = "footer">I'm the footer.</td></tr>
</table>

Example CSS:

html, body, .wrapper {
   height: 100%;   
}
.header {
    height: 100px; /*This value can be anything*/
}
.content {
    text-align: center;
}
.footer {
    height: 100px;
}

Demo: jsFiddle. Note how the content is centered both vertically and horizontally.

Hope that helped!

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!