Search code examples
javascripthtmlcssalignmentvertical-alignment

How to vertically align text in a container,


I searched this forum for such a long time but I couldn't find anything that could answer my question.

I have a container with two side by side sections. I want the text on the left side to vertically align center in its container based on the height of the container on the right side.

I used my-auto, m-auto, and several other bootstrap css classes, and also some of my custom ones, but none of them seemed to work.

Please see attached code to understand (open in a full page or expand the snippet so you can see the sections side by side)

<!DOCTYPE html>
<html>

<head>
  <!-- CSS -->
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
</head>

<body>
  <div>
    <div class="container-fluid">
      <div class="row">
        <div class="col-md-6 bg-light">
          <div class="m-auto p-5">
            <h2>Content that needs to be vertically aligned</h2>
          </div>
        </div>
        <div class="col-md-6 bg-primary">
          <div class="ml-5 space-top-2 space-bottom-2 pr-10">
            <div class="container">
              <div class="row space-bottom-2">
                <div class="col-md-3">

                </div>
                <div class="col-md-9">
                  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum egestas leo laoreet nunc congue, at venenatis risus tristique. Suspendisse ac augue metus. Donec finibus velit at accumsan tristique. Sed eu sapien sed purus fringilla
                    pretium. Curabitur ac nisl at massa vulputate hendrerit eget non urna. Praesent nec turpis vitae velit semper efficitur. Nullam a diam rutrum, venenatis nisl sit amet, placerat felis. Nullam semper, augue ut vestibulum venenatis, quam
                    tellus ornare enim, ut mattis nibh ante vitae dui. Nunc elementum, sem at aliquet vulputate, ipsum tellus volutpat arcu, ut imperdiet orci turpis sit amet velit. Sed et eros nec ipsum sagittis scelerisque vel at urna. Nunc ante lacus,
                    facilisis in feugiat et, pharetra sit amet orci. Nullam tincidunt ligula et nunc tempor posuere. Sed faucibus cursus urna, non porta tortor dignissim in. Nulla in urna et ligula fermentum imperdiet.</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</body>

</html>


Solution

  • By using flex in css, we can achieve this.

    <div class="col-md-6 bg-light h-100 d-flex align-items-center justify-content-center">
    

    Here, align-items-center makes the text vertically center and justify-content-center makes the text horizontally center.