twitter-bootstrap 如何使用 Bootstrap 4 在一行中居中文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47269402/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 01:08:14  来源:igfitidea点击:

How to center text in a row using Bootstrap 4

twitter-bootstrapbootstrap-4

提问by Samrat Luitel

The problem is that <p>and <h1>are appearing on same line and no matter what I do they can't be centered.

问题是<p><h1>出现在同一条线上,无论我做什么,它们都不能居中。

HTML

HTML

<div class="container">
  <div class="row" id="appSummary">
    <h1>Why This App Is Awesome</h1>
    <p class="lead">Summary, once again, of your app's awesomeness</p>
  </div>
</div>

CSS

CSS

#appSummary{
  text-align:center;
}

回答by Klooven

The best way to do this is to wrap the text in a column that has the class text-center.

执行此操作的最佳方法是将文本包装在具有 class 的列中text-center

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
<div class="container">
  <div class="row" id="appSummary">
    <div class="col text-center">
      <h1>Why This App Is Awesome</h1>
      <p class="lead">Summary, once again, of your app's awesomeness</p>
    </div>
  </div>
</div>



An other way to do this is to use the class justify-content-centeron the row, but without the column things may break.

另一种方法是justify-content-center在行上使用类,但如果没有列,事情可能会中断

回答by j08691

Since you're using Bootstrap 4 which uses the flex model, change your CSS rule to:

由于您使用的是使用 flex 模型的 Bootstrap 4,请将您的 CSS 规则更改为:

#appSummary{
    justify-content:center;
}

Bootply example

Bootply 示例

回答by Vico

You can use margin: autofor centering item, rather than text-align: centerwhy?

您可以margin: auto用于居中项目,而不是text-align: center为什么?

margin: 0 auto;affects the container directly, and when the container is block-level (display: block).

text-align: center;center affects text, inline, and inline-block level children of a container - not the container itself.

margin: 0 auto;直接影响容器,当容器是块级时(显示:块)。

text-align: center;center 影响容器的文本、内联和内联块级子级 - 而不是容器本身。

reference

参考

i created example in jsfiddle

我在jsfiddle 中创建了示例

回答by voscausa

Use d-flex flex-column : more here

使用 d-flex flex-column :更多在这里

<div class="container">
        <div class="d-flex flex-column" id="appSummary">
            <h1>Why This App Is Awesome</h1>
            <p class="lead">Summary, once again, of your app's awesomeness</p>

        </div>
 </div>