Vertical align <p> similar to how buttons text is vertically aligned when h-100 is applied in Bootstrap

Issue

To be clear, I’m using Bootstrap 5, and interested if there are native utilities to bootstrap to do this, but also happy just applying some CSS class/styling!

For example, if in a row I have 2 buttons & the text across the 2 buttons are of different heights, I can avoid the buttons-having-different-heights by applying h-100 to both buttons. I understand what’s happening is that since cols within a row have the same height, this singular height variable is now transferred to both buttons, so both buttons are the same height. This is visually evident when a border is applied.

<div class="row">
  <div class="col-6">
    <button class="btn btn-lg border border-primary w-100 h-100">Option A</button>
  </div>
  <div class="col-6">
    <button class="btn btn-lg border border-primary w-100 h-100">Much more involved option</button>
  </div>
</div>

I tried to do the same thing except with buttons, using <p> content. Again I use bg-color to visually represent what’s happening. I’m pleased that the shaded area has the same height regardless of the height of the text.

<div class="row">
  <div class="col-6">
    <p class="bg-secondary w-100 h-100">Text A</p>
  </div>
  <div class="col-6">
    <p class="bg-secondary w-100 h-100">Much more involved text</p>
  </div>
</div>

However, what the <p> example lacks that the <button> has, that I would like to add, is that the button text is vertically aligned relative to height of the total button object. I.e., the text Option A is positioned vertically in the center of the first button.

How would I position the shorter text Text A vertically in the center of the height shaded? Again, happy to have answer as Bootstrap native utility, or additional CSS styling.

See this Codeply, please view in mobile mode for what I’m talking about: https://www.codeply.com/p/wpoarBKYoy

Solution

You can do this by using Flexbox.

Try adding align-items-center to <p> like this:

<p class="bg-secondary d-flex align-items-center w-100 h-100">Text A</p>

Answered By – Payal Sen

Answer Checked By – David Marino (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.