2017-04-09 96 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>