Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do relatively positioned elements ignore floated elements

Tags:

css

When a static block element follows a floated element it will fill the remaining space available to it.

So, for example .right will take a width of 80%:

.left {
    background-color: red;
    float: left;
    width: 20%;    
}

.right {
    background-color: blue;
}

http://jsfiddle.net/yryZR/

However, when a block element with position: relative follows a floated element, the floated element seems to be ignored and the relative element takes 100% width:

.left {
    background-color: red;
    float: left;
    width: 20%;    
}

.right {
    background-color: blue;
    position: relative;
}

http://jsfiddle.net/yryZR/1/

According to the W3C "Once a box has been laid out according to the normal flow or floated, it may be shifted relative to this position" (source)

So if I am not changing the left or right positions of the element, why does it set itself to the very left of its parent element rather than stay in the normal flow?

like image 527
My Head Hurts Avatar asked Jan 26 '26 01:01

My Head Hurts


1 Answers

position:relative refers to the position the element would've been in had there been no CSS positioning overrides - e.g. its natural unaltered position.

floated elements are essentially removed from document positioning calculations, so your left element is invisible for the right element's positioning, so it takes the size of the next higher element - the container that these two left/right boxes are in.

like image 117
Marc B Avatar answered Jan 27 '26 14:01

Marc B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!