3 Ways to Vertically center text | CSS Only

vertically center text

Image or content are the soul of any website. Therefore content and images should be properly aligned according to content. To align center we use CSS property text-align:center or margin:auto.

But making things vertically center is not so easy. Here we will discuss the different ways of making objects vertically center/middle.

Vertical align If we know the containers width or height!

<style type="text/css">
    .posrel{position:relative;width:600px; height:400px;border:solid 1px #111;}
    .positioncenter{position:absolute; top:50%; left:50%; width:300px; height:200px; margin-left:-150px; margin-top:-100px; border:solid 1px #c33;}
</style>
<div class="posrel">
  <div class="positioncenter">
    Hello friends
    <p>kishan</p>
  </div>
</div>

Vertical align if we don’t width or height

CSS

<style type="text/css">
.clearfix:after,.clearfix:before{content:""; display:table; clear:both;}
.clearfix{clear:both;}


/**** Middle center object using display property  ***/
.imgcenterbox{width:400px; height:400px; border:solid 1px #ddd; display:table; float:left; margin-right:30px;}
.boxrow{display:table-cell; text-align:center; vertical-align:middle;}


/***************************/
.posrel{position:relative;width:600px; height:400px;border:solid 1px #111;}
.positioncenter{position:absolute; top:50%; left:50%; transform:translate(-50%,-50%); border:solid 1px #c33;}

/***************************/
.flexcss {display: flex;width:600px; height:400px;border:solid 1px #111;}
.child {margin: auto;border:solid 1px #c33;}
</style>

HTML

<!-- Using Display Property -->
<div class="clearfix">
  <div class="imgcenterbox">
    <div class="boxrow">
      <img src="img.jpg" />
    </div>
  </div>
  <div class="imgcenterbox">
    <div class="boxrow">
      I am containers content
      <p>Vertically center using display property</p>
    </div>
  </div>
</div>

<!-- Using Position Property -->
<div class="clearfix">
  <div class="posrel">
    <div class="positioncenter">
      I am containers content
      <p>Vertically center using Position property</p>
    </div>
  </div>
</div>


<!-- Using Flex Property -->
<div class="clearfix flexcss">
  <div class="child">
    I am containers content
    <p>Vertically center using Flex property</p>
  </div>
</div>