Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning CSS width to a position:fixed element

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:

  1. http://jsfiddle.net/2dudX/4/
    vs.
  2. http://jsfiddle.net/2dudX/10/

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?

like image 350
tim peterson Avatar asked Jan 15 '23 17:01

tim peterson


2 Answers

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)

like image 119
Dmitry Koroliov Avatar answered Jan 26 '23 00:01

Dmitry Koroliov


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());
});
like image 24
CoreyRS Avatar answered Jan 25 '23 22:01

CoreyRS