如何使用 Bootstrap 将容器右对齐?

now*_*wox 6 bootstrap-4

我想让一个元素与窗口的右上角对齐。我写了这个:

  <div class="container-fluid fixed-top">
    <div class="row">
      <div class="col-8"><!-- dummy --></div>
      <div class="col-4 alert alert-primary">Here I am!</div>
    </div>
  </div>
Run Code Online (Sandbox Code Playgroud)

问题是,如果我调整窗口大小,虚拟列会提供额外的垂直空间。

我尝试使用float-right,但我的div从容器中出来了。

有没有办法让我alert alert-primary有一个最小文本宽度(比方说20个字符)并右对齐?

mah*_*han 6

在其父级上使用d-flexand ,您可以做到这一点。justify-content-end

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/css/bootstrap.css" rel="stylesheet" />
<div class="container-fluid fixed-top">
  <div class="row">
    <div class="col-12 d-flex justify-content-end">
      <div class=" alert alert-primary">Here I am!</div>
    </div>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)


fixed-top将元素的位置更改为fixed并将其 top 属性更改为0。由于 的container意思fixed是从文档的正常流程中删除,因此您需要将其right位置设置为0移动到右侧。

Bootstrap 没有用于此类目的的类。因此,您需要使用自定义CSS.

.position-r-0 {
  right: 0 !important;
}
Run Code Online (Sandbox Code Playgroud)
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/css/bootstrap.css" rel="stylesheet" />
<div class="container-fluid fixed-top position-r-0">
  <div class="row">
    <div class="col-auto ml-auto alert alert-primary">Here I am!</div>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

可能存在一些对齐问题。如果是这样,请增加正确的位置,例如right: 5rem5px


Zim*_*Zim 5

你可以这样做(不需要额外的CSS)...

<div class="container-fluid fixed-top">
    <div class="row">
        <div class="ml-auto col-auto alert alert-primary">Here I am!</div>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

https://www.codeply.com/go/KeorPCu7AR

该类col-auto最小化列宽以适合其内容,然后ml-auto将其推到右侧。这样您就不需要虚拟列。

编辑

另外,最好将警报放在列中......

<div class="container-fluid fixed-top p-0">
    <div class="row">
        <div class="ml-auto col-auto">
            <div class="alert alert-primary">Here I am!</div>
        </div>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

另请参阅:右对齐 Bootstrap 容器,它也与默认容器对齐