2016-11-26 88 views
0

雖然很多帖子我搜索了Stackoverflow,但我沒有找到解決方案。使用margin的CSS邊距摺疊:auto;

我想垂直對齊我的文本,使用margin:auto;

似乎有一種緣崩潰的問題,如果你想查詢這個例子:

// HTML 
<div class="outer"> 
    <div class="inner">Hello</div> 
</div> 

<div class="outer2"> 
    <div class="inner">Trying to center this text vertically</div> 
</div> 

// CSS 
.inner { 
    margin: auto 0; 
    height: 20px; 
    color: white; 
} 
.outer { 
    background-color: red; 
} 
.outer2 { 
    background-color: blue; 
    height: 200px; 
} 

If you want to play on my code, click here

回答

1

我不相信有以垂直對齊使用margin: auto 0喜歡你」內容的好方法已經設置好了。要獲得inner div的垂直居中,這裏有一個簡單的方法,通過修改.inner

.inner { 
    height: 200px; 
    color: white; 
    line-height: 200px; 
} 
0

我會建議你使用Flexbox的 它添加到outer2類

.outer2 { 
    background-color: blue; 
    height: 200px; 
    display:flex; 
    align-items:center; 
} 

而對於水平對齊您可以使用justify-content:center align-item:center將對齊div中心的項目垂直,

1

顯示器沒有魔法。顯示:內部表格和顯示:外部div上的表格。最後在內部div上放置垂直對齊:中間或任何你想要的位置。

.inner { 
     display: table-cell; 
     vertical-align: middle; 
     height: 20px; 
     color: white; 
    } 
    .outer2 { 
     text-align: center; 
     background-color: blue; 
     height: 200px; 
     display: table; 
     width: 100%; 
    } 
0
.outer2 { 
    display: flex; 
    justify-content: center, left; 
    background-color: blue; 
    height: 200px; 
} 
0

您要對齊給予保證金整個內DIV:汽車。如果要對齊文字,可以使用文字對齊:居中。如果你需要對齊整個div,然後提到內部div的高度和寬度。我已經發布小提琴鏈接請

http://jsfiddle.net/ajaycoder/n1rz0bts/4/

.inner { 
    margin: auto ; 

    color: white; 
    width:50%; 
    border: solid 1px red; 
    height:50%; 
}