簡體   English   中英

我應該如何在垂直和水平方向上精確對准一個div?

[英]How should i center exactly a div both vertically and horizontally?

我是CSS的新手,但我嘗試了不同的東西,但我不能讓我的div垂直居中。

家長:

#ModalScroll{
    position:absolute;
    top:0;
    left:0;
    z-index:1001; 
    height:1px;
    width:1px;
    overflow:hidden;
    display:none;
    font-size:100%;
    text-align:left;
}

孩子:

.ModalDialog{
    border:1px solid #3C4749;
    background-color:#FFF;
    margin:0 auto 0 auto;
    display:none;
    font-size: 12px;
    box-sizing: border-box; 
    width: 280px;
    height: 160px; 
    position: absolute;
    left: 50%;
    top: 50%;
    margin: -80px 0 0 -140px;
}

我不知道jQuery中的解決方案是否應該更好,但我更喜歡CSS中的解決方案。

您是否使用過firebug以確保您的css已被充分利用? (也許其他CSS會重載項目的某些屬性......)

position:absolute; /*it can be fixed too*/
left:0; right:0;
top:0; bottom:0;
margin:auto;

應該做的伎倆(如在水平和垂直中心DIV中所說)可能嘗試為每個屬性添加“!important”...

編輯:這是帶有“!important”標記的CSS:

position:absolute !important;
left:0 !important;
right:0 !important;
top:0 !important;
bottom:0 !important;
margin:auto !important;

嘗試這個:

HTML

<div class="divContent">
    content goes here
</div>

CSS

.divContent {
    width: 200px;
    height: 300px;
    border: 1px solid red;
    position:absolute;
    left:0;
    right:0;
    top:0;
    bottom:0;
    margin:auto;
}

這是你的問題的代碼,

HTML代碼:


<div class="maindiv">
    <p class="hdiv">JSFIDDLE V</p>
</div>
<br>
<div class="maindivh">
    <p class="hdih">JSFIDDLE H</p>
</div>

CSS代碼:

.maindiv {   position:relative; border:1px solid #cfcfcf; height:50px; width:200px; }

.hdiv {width:200px; text-align:center; height:50px;}

.maindivh { position:relative; border:1px solid #cfcfcf; height:150px; width:200px; }

.hdih { vertical-align:middle; display:table-cell; line-height:150px; text-align:center; width:200px; }

演示

暫無
暫無

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

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