2017-04-09 144 views
0

如何在另一個div中居中div?怎麼樣一個圖像?我希望它垂直和水平居中。我想要現代化並使用flex - 我不關心舊的IE支持。如何在div中水平和垂直對齊元素

.outside { 
 
    background: orange; 
 
    width: 400px; 
 
    height: 300px; 
 
} 
 

 
.inside { 
 
    width: 80%; 
 
    background: yellow; 
 
}
<div class='outside'> 
 
    <div class='inside'> 
 
    This is the inside div that I would like to center in the outer one 
 
    </div> 
 
</div> 
 

 
--------------------------------------------------------------------------- 
 

 
<div class='outside'> 
 
    <img src="http://placehold.it/350x150"> 
 
</div>

回答

1

垂直於CSS定心總是麻煩比它應該是。這是一個使用Flex的簡單解決方案。 Flex不適用於所有瀏覽器!

需要寬度才能水平居中。

我知道有很多類似的問題,但我相信這種方法是快速和簡單的。

.outside { 
 
    background: orange; 
 
    width: 400px; 
 
    height: 300px; 
 
    
 
    /* This is the magic*/ 
 
    display: flex; 
 
    justify-content: center; /* This centers horizontally */ 
 
    align-items: center; /* This centers vertically */ 
 
} 
 

 
.inside { 
 
    width: 80%; /* Without a width, horizontally aligning "doesn't work"*/ 
 
    background: yellow; 
 
}
<div class='outside'> 
 
    <div class='inside'> 
 
    This is the inside div that I would like to center in the outer one 
 
    </div> 
 
</div> 
 

 
--------------------------------------------------------------------------- 
 

 
<div class='outside'> 
 
    <img src="http://placehold.it/350x150"> 
 
</div>