2014-03-03 35 views
1

我正在創建一個用於動態添加學生和教師的簡單應用程序。在動態創建的div問題中垂直居中文本

我正在點擊動態地添加div。

我已將「userListUnit」類添加到該div。

這是JS

SchoolAdmission.prototype.display = function(nameButton) { 
     var print = document.createElement("div"); 
     print.className = "userListUnit"; 
     print.innerHTML = "Name: " + this.name + ", age:" + this.age + ", depart: " + this.department + "<br><br><br>"; 
     if (nameButton === "addStudent") { 
      document.getElementById('studentList').appendChild(print); 
     } 
     else { 
      document.getElementById('teacherList').appendChild(print); 
     } 
     clearFields(); 
    }; 

這是CSS

.userListUnit{ 
    vertical-align: middle; 
    border: 1px solid; 
    text-align: center; 
    line-height: 10px; 
    box-shadow: 5px 5px 5px #888888; 
    margin-bottom: 2em; 
} 

我的小提琴http://jsfiddle.net/LPu9x/7/

嘗試加入一個學生或老師,並檢查文本在動態創建的div內的位置,然後您將瞭解其不是垂直居中的。 Any1有任何想法可以解決這個問題嗎?

條件:

1)無位置是:絕對的。

2)Div的創建仍然應該低於一個接一個。

更新小提琴解決方案http://jsfiddle.net/LPu9x/8/

+0

使用直列標籤如何使用'顯示:表細胞;'[此](http://stackoverflow.com/questions/ 18649106/DIV-垂直對齊,中間的CSS/18649137#18649137)? –

+0

我試過......塊出現在右側,而不是一個接一個下。 –

+0

使用'display:table;'將結果換行爲''width:100%' –

回答

3

試試這個:如果你想調整它,只需修改行高

.userListUnit 
{ 
    vertical-align: middle; 
    border: 1px solid; 
    text-align: center; 
    line-height: 15px; 
    box-shadow: 5px 5px 5px #888; 
    margin-bottom: 2em; 
    padding-top: 5px; 
    height: 30px; 
} 

...

看一看here

+0

我做了什麼錯誤? –

+0

嗯,你沒有設置一個高度..所以行高是「困惑」:)) – csanonymus

+0

上帝詛咒:D謝謝夥計.. –

1

如果將塊元素div更改爲內聯元素p不是您可以這樣做的問題,而vertical-align將按預期工作。當然,也可以刪除任何嵌套的br標籤,因爲CSS應該用於該標籤,即:padding/margin。

如果你可以將標籤更改爲p你的腳本是這樣的:

SchoolAdmission.prototype.display = function(nameButton) { 
    var print = document.createElement("p"); // p tag now 
    print.className = "userListUnit"; 
    print.innerHTML = "Name: " + this.name + ", age:" + this.age + ", depart: " + this.department; 
    if (nameButton === "addStudent") { 
     document.getElementById('studentList').appendChild(print); 
    } 
    else { 
     document.getElementById('teacherList').appendChild(print); 
    } 
    clearFields(); 
}; 

更改CSS行高度,以更大的東西像30px(因爲我們要刪除的br標籤上面:

.userListUnit{ 
    vertical-align: middle; 
    border: 1px solid; 
    text-align: center; 
    line-height: 30px; 
    box-shadow: 5px 5px 5px #888888; 
    margin-bottom: 2em; 
} 

就是這樣,您現在可以簡單地更改line-height屬性,並且文本始終保持垂直對齊。


DEMO - 具有垂直-align


+0

Thanx爲你的答案太:) 但我想一個div,你必須硬編碼.. –

+1

@NevinMadhukarK:或使用一個或兩個'position' /'table-cell'屬性的變化。這是因爲'div'是一個塊元素,'vertical-align'屬性用於'in-line level'和'table-cell'元素。根據[** W3C docs **](http://www.w3.org/wiki/CSS/Properties/vertical-align):'vertical-align屬性會影響框的行框內的垂直位置由內聯級元素生成 – Nope