Float right and position absolute doesn't work together
I want a div to be always at the right of its parent div, so I use float:right
. It works.
But I also want it to not affect other content when inserted, so I use position:absolute
.
Now float:right
doesn't work, my div is always at the left of its parent div. How can I move it to the right?
Solution 1:
Use
position:absolute;
right: 0;
No need for float:right
with absolute positioning
Also, make sure the parent element is set to position:relative;
Solution 2:
Generally speaking, float
is a relative positioning statement, since it specifies the position of the element relative to its parent container (floating to the right or left). This means it's incompatible with the position:absolute
property, because position:absolute
is an absolute positioning statement. You can either float an element and allow the browser to position it relative to its parent container, or you can specify an absolute position and force the element to appear in a certain location. Specifically, an element with position:absolute
will be placed at whatever offset you specify (with left
, right
, top
, or bottom
) from the position of its nearest ancestor (containing element) with a position
property, regardless of whether it has a float
property or not. If it doesn't have any ancestors with a position
property, it will be placed at your specified offset from the edge of the screen.
If you want an absolutely-positioned element to appear on the right side of its parent div
, you can use position: absolute; right: 0;
-- as long as the parent div
has a position property such as position:relative
. If the parent div
doesn't have a position property, though, this won't work, and you'll need to stick to float:right
.
Solution 3:
You can use "translateX(-100%)" and "text-align: right" if your absolute element is "display: inline-block"
<div class="box">
<div class="absolute-right"></div>
</div>
<style type="text/css">
.box{
text-align: right;
}
.absolute-right{
display: inline-block;
position: absolute;
}
/*The magic:*/
.absolute-right{
-moz-transform: translateX(-100%);
-ms-transform: translateX(-100%);
-webkit-transform: translateX(-100%);
-o-transform: translateX(-100%);
transform: translateX(-100%);
}
</style>
You will get absolute-element aligned to the right relative its parent
Solution 4:
Perhaps you should divide your content like such using floats:
<div style="overflow: auto;">
<div style="float: left; width: 600px;">
Here is my content!
</div>
<div style="float: right; width: 300px;">
Here is my sidebar!
</div>
</div>
Notice the overflow: auto;
, this is to ensure that you have some height to your container. Floating things takes them out of the DOM, to ensure that your elements below don't overlap your wandering floats, set a container div
to have an overflow: auto
(or overflow: hidden
) to ensure that floats are accounted for when drawing your height. Check out more information on floats and how to use them here.