屏幕中央的中心站点



我正在开发一个网站,想把这个网站集中在屏幕中央(水平和垂直),但不能。我只能水平居中。

由于我一直在搜索,当我尝试将它们应用于我的网站时,我找到了解决方案,所以这一切都被破坏了。

这是网站 http://amsdarquitetura.com.br/

这是你需要的:

<style type="text/css">
#global {
    position:absolute;
    width: 700px;
    height: 400px;
    margin-top: -200px; /* half of the height */
    margin-left: -350px; /* half of the width */
    left: 50%;
    top: 50%;
    border: 1px solid #333;
    background-color: pink;
}
</style>

把它放在你的父div 上。

为了引导您走上正确的道路,请尝试使用 JAVASCRIPT(可能想要添加标签)来检测 window.height。

// The window.innerHeight and document.body.clientHeight will make sure it is cross-browser compatible.
function getHeight() {
    return window.innerHeight != null? window.innerHeight: document.body != null? document.body.clientHeight:null;
}

然后减去主div 的高度。

var maindiv=500; //this is your total height of main div with content
var windowHeight = getHeight(); 
var displayHeight= windowHeight-maindiv;

然后除以 2(顶部/底部)

var topMargin= displayHeight/2;

最后,在主div中添加一个"边距顶部"。

document.getElementById('wrap').style.marginTop=topMargin;

水平很容易:

<style type="text/css">
    #wrap {
        margin: 0 auto;
        width: 800px;
    }
</style>
<body>
    <div id="wrap">
      [content]
    </div>
</body>

垂直要困难得多,并且可能需要CSS3或javascript定位。

您必须为整个网站定义高度和宽度,以使其在两个方向上居中。

从那里开始,它只是对垂直居中进行数学计算。水平是相当自动的,定义宽度并具有边距:0自动;(不要使用 5px 自动)。

这是一篇关于垂直居中的体面文章:

http://blog.themeforest.net/tutorials/vertical-centering-with-css/

有一个jQuery插件可以做到这一点。 我看到你已经在主页上使用jQuery了。

http://www.seodenver.com/simple-vertical-align-plugin-for-jquery/

正如您所发现的那样,执行此操作的CSS选项似乎很复杂,不可靠且笨拙。

你可以实现一个自定义的jQuery函数来做同样的事情。 但是,当其他人已经解决了问题时,为什么要维护该代码呢?

最新更新