Reputation: 7227
What is the difference between float:left
and float:right
within a parent with position:relative
? In my testing, both result in a div
being floating in the top-left corner of it's parent, overlaying the image (unless I manually position the div
using right: 0px
).
I can see a difference with position:absolute
. float:left
needs it to overlay the div
over the image, with float:right
I can omit it and still get the overlay effect.
Can anyone enlighten me what's going on here?
My problem is illustrated in this jsFiddle.
HTML:
<div class="parent">
<div class="tag">Featured</div>
<img src="http://www.placehold.it/200x200">
</div>
CSS:
.parent {
position:relative;
width: 200px;
}
.tag {
float: right;
position: absolute; /* can omit when using float:right */
/* right: 0px; */ /* uncomment to right-align child */
}
Edit:
I was mistaken with my statement about position:absolute
and float
. Somehow I got the impression when playing round with the jsFiddle, sorry for the confusion. Thanks for all your answers.
Upvotes: 2
Views: 1654
Reputation: 3675
Absolute positioning takes that element out of the normal flow. So when you try to use float it has no effect because it cannot flow within your .container to "float." You are telling it to ignore the rest of the elements for absolute positioning. With absolute positioning you have to state where you want it to reside within your parent. So @Francodi solution is correct. Just further explanation.
Upvotes: 2
Reputation: 5532
Float does neither affect elements that are position:absolute
nor the parent child relationship. It only concerns elements living on the same DOM level. float:left
will let the element float on the left and the other way round. clear: both
applied on an element stops the floating there:
Imho you are better of using display:inline-block
most of the times.
Upvotes: 0
Reputation: 891
You cannot use float
on an element that has set position: absolute;
. Just use left: 0;
or right: 0;
to align them inside the parent which has position: relative;
.
Also, position: relative
will not touch the float behaviour of your children. It is just the position: absolute
which disables the float functionality. which is the reason that your float: right
is also on the left top side. With position: absolute
you want to explicitly say where the element is located. floats do not fit into this role and will therefore have no effect.
Upvotes: 4