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

6

我希望将一个元素对齐到窗口的右上角。我写了这个:

  <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>

问题是,如果我调整窗口大小,虚拟列会给额外的垂直空间。
我尝试使用float-right,但我的div会超出其容器。
是否有一种方法只让我的alert alert-primary具有最小文本宽度(比如说20个字符),并且右对齐?
3个回答

6

通过在父元素上使用d-flexjustify-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>


fixed-top将元素的位置更改为fixed,并将其top属性设置为0。由于containerfixed类型的,这意味着它已从文档的正常流中移除,因此您需要将其right位置设置为0以将其移动到右侧。

Bootstrap没有为此目的提供类。因此,您需要使用自定义CSS

.position-r-0 {
  right: 0 !important;
}
<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>

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


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>

The col-auto class will adjust the column width to fit its content, and then ml-auto will push it to the right. This way, you won't need a dummy column. Edit: It would be better to place the alert inside the column.
Link: https://www.codeply.com/go/KeorPCu7AR
<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>

此外,请参见:右对齐的Bootstrap容器,也与默认容器对齐

0

使用 position: fixed,将其锚定在页面的顶部和右侧:

#fixed-div {
    position: fixed;
    top: 1em;
    right: 1em;
}

可以,但这不再是Bootstrap了。 - nowox

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接