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
)