簡體   English   中英

如何將網站與屏幕頂部/底部和右側/左側的中心對齊?

[英]How to align a website to the center of the screen top/bottom and right/left?

我想要像Dropbox這樣的效果: https : //www.dropbox.com/ ,我的網站位於頁面的正中間。

如果要實現此目的:

看起來如何

這是不同的方法,每種方法各有利弊,可以使頁面垂直居中。 選擇您喜歡的一個:

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

編輯。 如建議的那樣,我將繼續解釋其中一種方法。 僅當您已經知道元素居中放置的高度/寬度(鏈接包含更多方法)時,它才有效。 假設您所有的內容都在<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表現得像一張桌子,可以垂直對齊到中間。

實現這種效果比應該的要復雜得多。 這是一個簡單的工作示例: 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;
}

JSFiddle示例的屏幕截圖

如果要使其垂直居中對齊,請檢查此網頁: http : //www.jakpsatweb.cz/css/css-vertical-center-solution.html

如果您知道頁面的寬度和高度,則將內容包裝在以下div CSS中

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

在最上面的div上給margin:0 auto 0 auto; 還要為該div定義一些寬度。

首先創建所需寬度的主容器,然后將所有代碼放入主容器中。 例如

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

   </div>
</body>

而在CSS

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

您可以根據需要更改寬度

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

   </div>
</body>

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

嘗試這個:

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;
}

這是一個演示

包裝一個div並定義其寬度,使用margin:0 auto將div居中。

您可以使用Firebug瀏覽器擴展程序檢查網站的CSS。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM