Reputation: 29096
I would like to have an element aligned to the top right of the window. I wrote this:
<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>
The problem is that if I resize the window, the dummy column give an additional vertical space.
I tried to use float-right
, but my div
goes out from its container.
Is there a way just have my alert alert-primary
have a minimum text-width (let's say 20 chars) and being right aligned?
Upvotes: 7
Views: 17389
Reputation: 362390
You can do this (no extra 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
The col-auto
class minimizes the column width to fit its' content, and then ml-auto
will push it to the right. This way you won't need the dummy column.
Edit
Also, it would be better to put the alert inside the column...
<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>
Also see: Right aligned Bootstrap container which also aligns with default container
Upvotes: 6
Reputation: 14935
Using d-flex
and justify-content-end
on its parent, you can do so.
<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
change position of an element to fixed
and its top property to 0
. Since the container
is fixed
meaning it is removed from the normal flow of the document, you need to set its right
position to 0
to move to the right side.
Bootstrap does not have classes for such a purpose. So, you need to use custom 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>
There might be some alignment issue. If so, increase the the right position, eg right: 5rem
or 5px
.
Upvotes: 6
Reputation: 3950
Use position: fixed, and anchor it to the top and right sides of the page:
#fixed-div {
position: fixed;
top: 1em;
right: 1em;
}
Upvotes: 0