如何使用Bootstrap将容器对齐?

时间:2018-05-18 12:24:27

标签: 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>

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

我尝试使用float-right,但我的div从其容器中消失。

有没有办法让我的alert alert-primary具有最小文字宽度(让我们说20个字符)并且正确对齐?

3 个答案:

答案 0 :(得分:2)

在其父级上使用QImaged-flex,即可。

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>将元素的位置更改为fixed-top,将其顶级属性更改为fixed。由于0container意味着它已从文档的正常流程中删除,因此您需要将其fixed位置设置为right以移至右侧。

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

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: 5rem

答案 1 :(得分:2)

你可以这样做(没有额外的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>

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>

答案 2 :(得分:0)

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

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