简体   繁体   English

Bootstrap 4 在 div 中垂直居中文本

[英]Bootstrap 4 vertically center text in div

I have this simple HTML code (with Bootstrap) :我有这个简单的 HTML 代码(使用 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).我只想将 div 中的文本“文本居中”垂直居中,保持边框与示例中的一样(不降低高度)。

I have tried things such my-auto or align-items-middle , also read questions asked before, but without success.我尝试过诸如my-autoalign-items-middle ,也阅读了之前提出的问题,但没有成功。

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:您可以在 Bootstrap 中使用 Flex 框预定义类:

 <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.尝试将my-auto添加到行内的第一个 div。

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

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

The answer is to add d-flex align-items-center to the element答案是在元素中添加d-flex align-items-center

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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