如何将网站对齐屏幕顶部/底部和右/左中心?

时间:2013-12-19 05:48:03

标签: javascript php css html

我希望得到像dropbox这样的效果:https://www.dropbox.com/我的网站位于页面的正中间。

9 个答案:

答案 0 :(得分:1)

如果你想实现这个目标:

How it looks

以下是不同的方法,每个方法的优点/缺点,用于垂直居中页面。选择你喜欢的那个:

  

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

EDIT。如上所述,我将继续解释其中一种方法。它只有在您已经知道要居中的元素的高度/宽度时才有效(链接包含更多方法)。假设您的所有内容都在<body>之内,并且您的内容为900px x 600px,那么您可以在css中执行此操作:

html {
  width: 100%;
  height: 100%;
  }
body {
  width: 900px;
  height: 600px;
  position: absolute;
  top: 50%;
  margin-top: -300px; /* Half of the height of your body */
  }

但是,这对于动态生成的内容来说是不够的,因为您不知道它的高度。我在登录框弹出和设置弹出窗口中成功使用了它。

我过去用于整个页面的另一种方法是链接中的方法1。它使一组div表现为一个表,它可以垂直对齐到中间。

答案 1 :(得分:1)

实现这种效果比应该更复杂。这是一个简单的工作示例:http://jsfiddle.net/jshado1/UEsYM/

html, body { height: 100%; } // needed for vertical centre

html { width: 100%; } // needed for horizontal centre

body {
    display: table; // needed for vertical centre
    margin: 0 auto; // needed for horizontal centre
    width: 50%; // needed for horizontal centre
}

.main-container {
    background-color: #eee;
    display: table-cell; // needed for vertical centre
    height: 100%; // needed for vertical centre
    // overflow: auto; // <- probably a good idea
    vertical-align: middle; // needed for vertical centre
    width: 100%; // needed for horizontal centre
}

.container {
    background-color: #ccc;
    padding: 20px;
}

screenshot from JSFiddle example

答案 2 :(得分:0)

如果您想将其垂直居中对齐,请查看此网页:http://www.jakpsatweb.cz/css/css-vertical-center-solution.html

答案 3 :(得分:0)

如果您知道页面的宽度和高度 然后将你的内容包装在下面的div css

.center
{
position:absolute;
top:50%;
left:50%;
margin-left: -(yourPageWidth/2);
margin-top: -(YourPageHeight/2);
}

答案 4 :(得分:0)

在你最上面的div上给出 margin:0 auto 0 auto; 还为该div定义一些宽度。

答案 5 :(得分:0)

首先创建一个所需宽度的主容器,然后将所有代码放在主容器中。对于例如。

<body>
   <div id="container">
     ......... your code

   </div>
</body>

在css中

#container{
  width: 700px ;
  margin-left: auto ;
  margin-right: auto ;
}

您可以根据需要更改宽度

答案 6 :(得分:0)

<body>
   <div class="container">
     ......... your code

   </div>
</body>

#container{
  width: 700px ;
  margin:0 auto ;
  padding:0px;
}

答案 7 :(得分:0)

试试这个:

HTML

<span id="forceValign"></span><!--
--><div id="centerMiddleWrap">
  <div id="centered">Hello this is some text. Hello this is some text. Hello this is some text.</div>
</div>

CSS

html {
    height: 100%;
    background: #eee;
 }
 body {
   margin: 0;
   height: 100%;
   /*important*/
   text-align: center;
 }
 #centerMiddleWrap {
  /*important*/
    display: inline-block;
    vertical-align: middle;
 }
 #forceValign {
   /*important*/
    height: 100%;
    display: inline-block;
    vertical-align: middle;
 }
#centered {
    background: #000;
    color: #fff;
    font-size: 34px;
    padding: 15px;
    max-width: 50%;
    /*important*/
    display: inline-block;
}

Here is an demo

答案 8 :(得分:-1)

包裹div并定义其宽度,使用margin:0 auto将div居中。

您可以使用 Firebug 浏览器扩展程序来检查网站的CSS。