i have a page where i have two div elements with different relative and fixed positioning.
<div class="outer1">
</div>
<div class="outer2">
</div>
and css is
.outer1{
width:50%;
height:500px;
background:red;
position:relative;
}
.outer2{
width:50%;
background:blue;
height:200px;
position:fixed;
}
But the problem is that the actual width of both the div elements is different. i have given width as 50% to both element then why there is difference in width.please help.
Your div .outer1
is taking width: 50%
of its parent i.e. body
.
Whereas you div .outer2
is positioned fixed
and therefore is removed form normal document flow and will position itself with respect to viewport.
Since every browser applies default 'user agent' stylesheet which includes default margin, paddings for elements therefore width of your document differs from that of viewport, that's why there is slight difference in the widths.
You can reset default browser styles, to get the desired result.
html, body {
margin: 0;
padding: 0;
}
When you use Position:fixed
the the div
takes whole container (i.e. body) as a reference.
A fixed position element is positioned relative to the viewport
, or the browser window itself.
In this case width of your screen is taken.Including the Extra default Margin of Body.
And When you set Relative to any Element it means "relative to itself". The element doesn't care about any rules.
That's why You are getting .outer
div extra long.Because it is not following the rules of Body tag.
When You use margin:0
then you can see the effect both are same.
JSFIDDLE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With