How to Center align div vertically using css?

During the early days of HTML development, to vertically center align a div or an element we used lots of methods or technique to achieve this. We used CSS position property in some cases and in some cases to do it in dynamically we used JavaScript to vertically align a div or an element. But in modern Flex-box solution it is the easy to do this. Just by using CSS ” justify-content: center” to the parent element to align the content to the center (vertically) of it. Most of the modern browser supports this CSS property.

How to Center align div vertically?

Here is code of one of the old solution to center align div vertically

<!DOCTYPE html>
<html>
   <head>
      <title>How to Center align div vertically?</title>
      <style id="compiled-css" type="text/css">
         .parent{
         position:relative;
         height:400px;
         }
         .center {
         background-color: green;
         color:#fff;
         position: absolute;
         left: 50%;
         top: 50%;
         transform: translate(-50%, -50%);
         -ms-transform: translate(-50%, -50%); /* for IE */
         -webkit-transform: translate(-50%, -50%); /* for Safari */
         width: 100px;
         height: 100px;
         }
      </style>
   </head>
   <body>
      <div class="parent">
         <div class="center">
            centered
         </div>
      </div>
   </body>
</html>

Here you go the easiest way(flex-box solution) of doing this:

<!DOCTYPE html>
<html>
   <head>
      <title>How to Center align div vertically?</title>
      <style id="compiled-css" type="text/css">
         .parent {
         display: flex;
         align-items: center;
         }
         .parent div{
         padding:10px;
         }
      </style>
   </head>
   <body>
      <div class="parent">
         <div>Sample Text</div>
         <div>
            Paragraph
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse imperdiet pulvinar quam. Pellentesque laoreet lacus non purus molestie, ac lobortis dolor volutpat. Suspendisse accumsan sem eu arcu luctus, eget feugiat dolor suscipit. Nulla sodales, elit ac blandit aliquam, mauris mi gravida mauris, a blandit dolor leo vel lectus. Nunc sit amet eros quis felis dapibus euismod vitae quis felis. Etiam ultricies ligula ut semper finibus. Etiam malesuada metus vel auctor luctus. Aliquam neque ligula, bibendum ac risus eu, ullamcorper suscipit turpis.</p>
         </div>
         <div>Image<img src="http://www.infopitcher.com/wp-content/uploads/2019/12/850FAAF0-851D-4FAF-B145-289F42DFC588.jpeg" width="50"></div>
         <div>Another Sample Text</div>
      </div>
   </body>
</html>

Leave a Reply

Your email address will not be published. Required fields are marked *