2016-12-15 84 views
0

使用固定高度的容器时,我只需简单地将行高属性与高度匹配即可。 未指定容器高度时如何操作?未指定父高度时的垂直居中文本

+0

'垂直对齐:基线|长度|分|超级|顶|文顶|中部|底部|文本底部|初期|继承;' –

回答

1

有几种方法。这是表格方法。另一种方法是使父容器相对并使p标记绝对顶部:50%;. 如果您不支持ie8或更低版本,则可以使用flexbox。这里是一个很好的资源,了解Flexbox的:http://flexboxfroggy.com/

.container{ 
 
    width: 300px; 
 
    height: 400px; 
 
} 
 

 
.content{ 
 
    width: 100%; 
 
    height: 70%; 
 
    display: table; 
 
} 
 

 
p{ 
 
    display: block; 
 
    display: table-cell; 
 
    vertical-align: middle; 
 
}
<div class="container"> 
 
    <div class="content"> 
 
    <p> 
 
    Center text 
 
    </p> 
 
    </div> 
 
</div>

1

#services .txt { 
 
    height: 500px; 
 
    border: 1px #000 solid; 
 
    display:table; 
 
    text-align:center; 
 
} 
 
.sub{ 
 
    display:table-cell; 
 
    vertical-align:middle; 
 
    text-align:center; 
 
}
<div id="services"> 
 
     <div class="txt"> 
 
      <div class="sub"> 
 
        <h1>Lorem Ipsum</h1> 
 
        <p> Lorem Ipsum is simply dummy text of the       printing and typesetting industry. Lorem       Ipsum has been the industry's standard       dummy text ever since the 1500s.. 
 
        </p> 
 
      </div> 
 
     </div> 
 
</div> 
 

现在试着改变的div .TXT高度,你会看到它的垂直定向的中心文本。

这种方式取决于使主分区显示:表;
and sub div display:table-cell;vertical-align:middle;

+0

但你指定一个高度,我寻找与未指定高度容器一起工作的东西。如果您删除#services .txt高度并使用更高的div将.sub浮动,那么您会注意到子内容不再是垂直居中。 – Crasher

+0

我告诉过你试着改变高度,文字会保持居中 –

+0

这不是我要找的,我不想改变高度,我不想指定这个属性! – Crasher

0
.support-box { 
     width: 50%; 
     float: left; 
     display: block; 
     height: 20rem; /* is support box height you can change as per your requirement*/ 
     background-color:#000; 
    } 
    .wrapper { 
     width: 50%; 
     display: block; 
     position: relative; 
     top: 50%; 
     transform: translateY(-50%); 
     background:#ddd; 
     margin:auto; 
     height:100px; /* here the height values are automatic you can leave this if you can*/ 

    } 
    .text { 
     width: 100%; 
     display: block; 
     padding:10px; 
     margin:auto; 
    } 


    <div class="support-box"> 
    <div class="wrapper"> 
    <div class="text">USE OUR DESIGNS</div> 
    </div> 
    </div> 

Js fiddle:// https://jsfiddle.net/vh4y426f/5/ 
+0

https://jsfiddle.net/vh4y426f/5/ –