简体   繁体   中英

Center element with percent size against page size

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

I can do this with vh and vw units ( 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 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 a div version. Can anyone provide any help?

A common way of displaying a divider 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% width and height of #wrapper which is 100% width and height of the page body.

As #wrapper is displayed as a table-cell within a body displayed as table , the content within will be affected by the vertical-align:middle property, causing the #inner divider to be in the vertical middle of the page.

Applying margin:0 auto; to the #inner divider then aligns it to the horizontal middle.


The beauty of this is that you don't need to worry about offsetting the #inner divider, and aren't limited to just using percentage widths. Fixed widths will still be aligned in the middle of the containing #wrapper .

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

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