Crasher
Crasher

Reputation: 2523

Vertically center text when parent height is unspecified

With a fixed height container I would simply make the line-height property match the height. How do you do it when container height is not specified?

Upvotes: 0

Views: 552

Answers (3)

Imran Mohammed
Imran Mohammed

Reputation: 228

    .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/

Upvotes: 0

Yahya Essam
Yahya Essam

Reputation: 1912

#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>
    

now try to change div .txt height and you will see it's vertical aligned center text .

this way is depend on make main div display:table;
and sub div display:table-cell; and vertical-align:middle;

Upvotes: 1

Yasin Yaqoobi
Yasin Yaqoobi

Reputation: 2050

There are couple of ways. Here is the table approach. Another way is to make parent container relative and make the p tag absolute with top:50%;. If you are not supporting ie8 or below you can use flexbox. Here is a great resource to learn 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>

Upvotes: 1

Related Questions