there is a hat:

.header{ height: 45px; } 

and there is a footer pressed to the bottom of the page:

 .footer { position: absolute; left: 0; bottom: 0; height: 45px; } 

and there is a central block with a fixed height:

 .center{ height: 350px; } 

it is necessary to make it so that .center is always vertically centered between .header and .footer. Those. if I reduce the height of the browser window in height, the .center should still be automatically aligned vertically in the center. Naturally, if I strongly compress the browser window, the footer will climb on the .center - and so it was conceived.

3 answers 3

Try using margin: 0 auto; but also insert the width of the block, i.e.

 .center{ height: 350px; width:1200px; margin:0 auto; } 
  • I tried it right away. He attaches to the cap, but you need, regardless of the size of the screen, so that the .center would be exactly halfway between the cap and the footer. - Vitaliy Fesyura
  • so you need to position your center absolutely, update the answer - Arsen

Modified the answer, painted the elements for clarity.

 .header{ height: 45px; background:#CCC} .center{ height: 350px; display:block; background:green; } .centered { position: fixed; top: 50%; left: 50%; /* bring your own prefixes */ transform: translate(-50%, -50%); } .footer { position: absolute; left: 0; bottom: 0; height: 45px; background:#F00; width:100%; } <div class="header">Header</div> <div class="centered"> <div class="center">Just some text</div> </div> <div class="footer">Footer</div> 

http://www.bootply.com/6cVBW44Sw4#

  • And if the height of the footer is not equal to the height of the cap, for example 300px. Then my center with a height of 200px will no longer be in the center vertically between the footer and the cap. - Vitaliy Fesyura
  • Modified the answer, painted the elements for clarity. Alignment takes place in the div BETWEEN the header and the footer. - labris

Add a central container .container between the footer and the header with a height of 100vh , subtract the height of the header and footer height: calc(100vh - 45px - 45px) from this value and add display: flex to it so that you can quickly center the block inside. Add a margin: auto property to the .center block to center it vertically and horizontally.

 * { box-sizing: border-box; } body { margin: 0; } .header { height: 45px; background-color: #ccc; } .footer { position: absolute; left: 0; bottom: 0; height: 45px; width: 100%; background-color: #666; } .center { height: 350px; margin: auto; border: 1px solid; } .container { height: calc(100vh - 45px - 45px); /* от полной высоты окна вычитаем высоту футера и хедера */ min-height: 350px; display: flex; } 
 <div class=header> header </div> <div class=container> <div class=center> Hello, I'm at center of this page </div> </div> <div class=footer> footer </div>