2017-07-20 133 views
1

我想要一個垂直和水平居中的div,即在頁面的中心。我嘗試了位置:絕對,並使div的右上角0左上!但問題是,當我放大與其他標題和其他div重疊的頁面!請幫幫我!如何在放大頁面時將div放置在頁面中心而不與其他div重疊?如何在頁面中心對齊div?

就像我曾嘗試:

.center{ 
     position: absolute; 
     top: 0; 
     bottom: 0; 
     left: 0; 
     right: 0; 
     margin: auto; 
} 
+0

嘗試設置保證金'auto' –

+0

糟糕!我忘了在我的代碼中提到margin:auto。我已經嘗試過,但仍然不起作用 – Fred

+1

試試這個... https://jsfiddle.net/DChandraShekhar/8a7L8dtv/1/ –

回答

1

html, body { 
 
    height:100%; 
 
} 
 

 
.center { 
 
    border: 2px solid blue; 
 
    margin: auto; 
 
    position: relative; 
 
    text-align: center; 
 
    top: 50%; 
 
    width: 20%; 
 
}
<div class="center"> 
 
    <p>Test Text</p> 
 
</div>

0

嘗試這個

HTML

<div class="center"> 
    Lorem ipsum dolor sit amet, 
</div> 

CSS

html,body{ 
    height:100%; 
} 
.center{ 
    position: relative; 
    top:50%; 
    left:50%; 
} 

Link for reference

希望這有助於..

1

嘗試,

html{ 
 
    height:100%; 
 
} 
 
body 
 
{ height:100%; 
 
    background-color: #fcfcfc; 
 

 
} 
 
.center 
 
{ 
 
    position: absolute; 
 
    margin: auto; 
 
    top: 0; 
 
    right: 0; 
 
    bottom: 0; 
 
    left: 0; 
 
    width: 100px; 
 
    height: 100px; 
 
    background-color: #ccc; 
 
    border-radius: 3px; 
 
}
<div class="center"></div>

0

水平居中塊元素(如DIV),使用餘量:汽車

.center { 
 
    margin: auto; 
 
    width: 60%; 
 
    border: 3px solid #73AD21; 
 
    padding: 10px; 
 
}
<div class="center"> 
 
    <p><b>Note: </b>Using margin:auto will not work in IE8, unless a !DOCTYPE is declared.</p> 
 
</div>

0

Flex是最好的解決方案,完美的位置。

如果你想要一個加載器,只需要一個固定位置的全尺寸div,並使用flex的div內容。

柔性引導https://css-tricks.com/snippets/css/a-guide-to-flexbox/

body, html { 
 
    height:100% 
 
} 
 

 
body { 
 
    display:flex; 
 
    margin:0; 
 
    flex-direction:column; 
 
} 
 

 
.mydiv { 
 
    margin:auto; 
 
}
<div class="mydiv">test</div>

+0

我也認爲flex是最好的解決方案。只要注意一些舊的瀏覽器 - 它可能需要另一種解決方案。 您可能不應該在身體上使用flex以避免影響頁面上的所有其他元素。相反,將它用在圍繞你的中心div的wrapper-div上。 Like

test
根據需要給包裝100%寬度和高度以及位置固定或絕對。 – Ina

+0

這仍然行不通! div在放大頁面時與其他元素重疊!我想修復它的位置 – Fred