简体   繁体   中英

Bootstrap 4 vertically center text in div

I have this simple HTML code (with Bootstrap) :

<div id="accordion">
  <div class="card">
    <div class="card-header" id="@itm.Id">
      <div class="row">
        <div class="col-2 border rounded text-center">
          text to center
        </div>
        <div class="col-2 border rounded text-center">Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute
        </div>
      </div>
    </div>
  </div>
</div>

I just want to vertically center the text "text to center" in the div, keeping the border as it is in the exemple (no height decrease).

I have tried things such my-auto or align-items-middle , also read questions asked before, but without success.

If possible I don't want to add classes (use existing bootstrap).

Here is the Fiddle : Vertically center text

You can used Flex box predefine class in Bootstrap for that:

 <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/> <div id="accordion"> <div class="card "> <div class="card-header" id="@itm.Id"> <div class="row"> <div class="col-2 border rounded justify-content-center d-flex align-items-center"> text to center </div> <div class="col-2 border rounded text-center"> ssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss </div> </div> </div> </div> </div>

For Information you can read here .

Try adding my-auto to the first div inside the row.

<div class="col-2 border rounded text-center my-auto">

https://jsfiddle.net/7zm40xj9/7/

The answer is to add d-flex align-items-center to the element

Example

If you had this:

<div class="col-3">

change it to this:

<div class="col-3 d-flex align-items-center>

请使用类: justify-content-center

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM