div中的內容水平垂直居中

1. div高度自適應的狀況css

    div在不設置高度的時候,會被裏面的內容撐開,內容自動填充在div中,不管是一行內容仍是多行內容,此時不須要設置垂直居中,內容自動在中間的,css3

    想要看的更直觀些,只須要加上padding元素,內容四周便會留下空白,實現水平垂直居中的效果web

    css代碼以下:瀏覽器

.demo{
    width: 200px;
    border: 1px solid red;
    padding: 20px;
 }

 HTML代碼以下:佈局

<div class="demo">
        this is a test of margin 
        this is a test of margin 
        this is a test of margin 
        this is a test of margin 
        this is a test of margin         
 </div>

效果以下所示:flex

2.div設置具體高度this

  (1)內容只有一行spa

   設置div的line-height和div的高度同樣便可,這個你們都知道噠code

  (2)內容不肯定有幾行orm

   這時候須要在div中再加一層結構,用p標籤或者div均可以

   方法一:

   css代碼以下:

.demo{
    position: absolute;
    width: 200px;           
    height: 200px; 
    border: 1px solid red;
}
 p{ 
    position: absolute;
    width: 150px;
    top: 50%;
    left:50%;
    transform: translate(-50%,-50%);
    border: 1px solid black;
 }

 HTML代碼以下:

<div class="demo">
     <p>
        this is a test of margin 
        this is a test of margin 
        this is a test of margin 
        this is a test of margin  
     </p>           
</div>

  效果以下:

   

方法二:如果不想用position:absolute這樣的脫離文檔流的樣式,那就能夠嘗試模擬表格的方法

   設置父元素display:table,設置子元素display:table-cell,並設置vertical-align:middle便可

   css代碼以下:

.demo{
    width: 200px;           
    height: 200px; 
    display: table;
    border: 1px solid red;
}
 p{ 
    display: table-cell;
    vertical-align: middle;
    text-align: center;
    border: 1px solid black;
 }

HTML代碼以下:

<div class="demo">
     <p>
        this is a test of margin 
        this is a test of margin 
        this is a test of margin 
        this is a test of margin  
    </p>           
 </div>

    效果以下所示:

    

  此時子元素設置寬度是沒用的,寬度始終和父元素一致;

  可是若是子元素設置高度的話,如果高度小於父元素則無效果,如果高度大於父元素則父元素的高度也相應增長到和子元素同樣的高度

 

方法三:

  使用css3新增的flex佈局完成。

  設置父元素display:box;  box-pack:center;  box-orient:vertical;便可,記得要在前面加上瀏覽器前綴哦

  css代碼以下:

.box{
    width: 200px;
    height: 200px;
    border: 1px solid red;
    display: box;
    box-pack:center;
    box-orient:vertical;
    display: -webkit-box;
    -webkit-box-pack:center;
    -webkit-box-orient:vertical;
}

HTML代碼以下:

<div class="box">
        <div>
            this is a test
            this is a test
            this is a test
        </div>
        <div>
            this is another test for the second div    
        </div>
</div>

效果顯示以下:

 

(by新手小白的記錄)

相關文章
相關標籤/搜索