Center element with percentage of page size

I need to center the div vertically and horizontally, and its size is a certain percentage of the entire page (say, 80%).

I can do this with vh and vw elements ( link )

<style> html, body { height: 100%; width: 100%; margin: 0; } body > div { position: absolute; background-color: red; top: 10vh; left: 10vw; width: 80vw; height: 80vh; } </style> <div></div> 

... or with an old table design ( link )

 <style> html, body { margin: 0; height: 100%; } #center { background-color: red; } </style> <table height="100%" width="100%"> <tr height="10%"></tr> <tr> <td width="10%"></td> <td id="center"></td> <td width="10%"></td> </tr> <tr height="10%"></tr> </table> 

But I would like to support the div version. Can anyone help?

+4
source share
1 answer

A common way to display a separator in the middle of a page is to display it as a table with a table cell:

 <body> <div id="wrapper"> <div id="inner"> </div> </div> </body> 
 html, body { margin:0; height:100%; } body { display:table; width:100%; } #wrapper { display:table-cell; vertical-align:middle; height:100%; width:100%; } #inner { height:50%; width:50%; margin:0 auto; } 

JSFiddle example .

In this example, #inner is 50% of the width and height of #wrapper , which is 100% of the width and height of the page body.

Since #wrapper displayed as a table-cell inside the body displayed as table , the contents inside will depend on the vertical-align:middle property, with the result that the #inner is in the vertical middle of the page.

Application margin:0 auto; to the divider #inner then aligns it horizontally.


The beauty is that you don’t have to worry about shifting the #inner divisor and not just go for the percentage width. The fixed width will still be aligned in the middle of the containing #wrapper .

This is supported in all modern browsers: http://caniuse.com/#feat=css-table

+2
source

Source: https://habr.com/ru/post/1483669/


All Articles