2016-12-15 82 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/ –