0

我一直在研究这个问题很长时间,但我并不幸运。这是情况。假设您在页面中心有一个蓝色矩形。当你全屏时,我们可以使用百分比的高度和宽度来保持矩形的比例。但是,矩形的位置发生了变化,它向上移动,最终在页面底部有额外的空间。

那么当启用全屏模式时,我应该怎么做才能使矩形保持在页面的中心(垂直和水平距离相等)?换句话说,如果你的屏幕是 1280x800,矩形的中心在 (640,400)

如果您查看 Chrome 浏览器的主页,当您全屏时,应用程序的位置保持不变,并且您最终不会在底部留出多余的空间。感谢你的帮助

4

3 回答 3

4

定义width矩形并使用margin: 0 auto;它在页面中水平居中。

如果你想div水平和垂直居中,使用这样的东西

HTML

<div id="rectangle"></div>

CSS

#rectangle {
   width: 30%; //can set any value here
   height: 20%; //can set any value here
   position: absolute;
   left: 50%;
   top: 50%; 
   margin-left: -15%; //negative half of width
   margin-top: -10%; //negative half of height
   background-color: red;
}​

看这里的小提琴。

或者

HTML

<div id="wrapper">
  <div id="container">
    <div id="rectangle"></div>
  </div>
</div>​

CSS

body, html {
    height: 100%;
    overflow:hidden;
}
#wrapper {
    width: 100%; 
    height: 100%; 
    overflow: visible; 
    position: relative;
}
#wrapper[id] {
    display: table; 
    position: static;
}
#container[id] {
    display: table-cell; 
    vertical-align: middle; 
    width: 100%;
}
#rectangle {
    width: 200px; 
    height: 100px; 
    margin-left: auto; 
    margin-right: auto; 
    background-color: blue;
}

​看这里的小提琴。

于 2012-07-13T17:09:41.573 回答
1

哎呀,

我忘记了我正在使用 iMac。脚本中的 if 添加解决了我的问题。

function vertical_center()
{
    var ww = $(window).width();
    if (ww < 1600)
    {
    $("#character").css({'width': ww + 'px','height': (ww/4) + 'px', 'margin-top': -(ww/8) + 'px'});
    }
    else
    $("#character").css({'width': ww + 'px'})
}

但是,如果有人查看我的代码并告诉我一些愚蠢的事情还存在哪里,我会很高兴。希望这篇文章能增加一些东西,谢谢大家

于 2012-09-12T05:33:50.163 回答
1

您是否也尝试过使用百分比作为边距,例如,如果您的中心正方形是 60% 高和宽,您可以添加 20% 作为边距,这样也可以扩大。没有尝试,我不知道它是否会给你想要的效果,但它应该解决正方形向上移动的问题。

于 2012-07-13T17:08:06.247 回答