2016-11-26 98 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%; 
}