I'd like a fixed element's width to match that of the div placed immediately below it. Imagine a header and a main content div. A problem in matching their widths occurs when the header and content divs are nested inside an outer div. In this scenario the % widths of each no longer match their parents width (e.g.,<body>
tag) and the fixed element's width is based on something which is confusing me.
To better explain what I mean, contrast these two js fiddles:
here's the code for each:
<div id="fixed"></div>
<div id="content"></div>
#fixed{ position:fixed; z-index:2; width:90%;
height:25px; background:yellow;}
#content{ width:90%; height:300px; background:red}
vs.
<div id="main">
<div id="fixed"></div>
<div id="content"></div>
</div >
#main{ width:95%}
#fixed{ position:fixed; z-index:2; width:90%;
height:25px; background:yellow;}
#content{ width:90%; height:300px; background:red}
Note only in jsfiddle #1 do the yellow and red divs widths match up regardless of how you resize the browser. Unfortunately, jsfiddle#2 is more of a real world scenario and I'm wondering how to correct the id="fixed"
div such that its width also matches up with id="content"
div.
Thoughts?
You can to it this way FIDDLE (to set % relative to the #main)
fixed element's dimensions always is calculated relative to the root element, so you need to reset %
-unit accordingly
in this particular case you need to set:
#fixed {
width: 85.5%;
}
It is case #main
is 95%, your static element is 90% relative to the main. So you need to calculate its width towards the root element (1
* .95
* .9
= .855
)
Easy one my friend. Fixed width elements are yanked from their parents and are now relative in width to the window, so in both situations the fixed div is always relative to the size of the window, but when in a parent container with a width other than 100% the fixed element will remain relative to the window width but the non-fixed position element is now relative to the parent width. So the non-fixed element became 90% of the 95% of the window while the fixed element remained a constant 90% of the window only.
Edit:
If you wish to match the widths you can use jquery like this:
$(function(){
$('#fixed').width($('#content').outerWidth());
});
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