Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Position fixed element with percentage width relative to container

I know that position: fixed makes an element relative to the viewport instead of it's offsetParent however I have an issue where I have a side element which takes x amount of space and then some fixed position heading elements which I want to take up a percentage of the remaining viewport width.

See fiddle: http://jsfiddle.net/U5DSZ/

Now I could put all the h1 element's into their own container but then they lose their semantic meaning as they are no longer associated with their content.

I understand JavaScript could do this but I am against using JavaScript for page structure.

Is there a way to do this in a purely HTML or CSS way? I don't mind moving the h1 element's as long as they retain their relationship with the content and the content remains statically positioned.

like image 519
George Reith Avatar asked Jun 03 '13 15:06

George Reith


1 Answers

You can get the effect that you want as follows.

Your HTML snippet is good as is:

<div id="content">
    <section>
        <h1>Heading 1</h1>
        <p>...</p>
    </section>
    <section>
        <h1>Heading 2</h1>
        <p>...</p>
    </section>
</div>

and the CSS is good but just requires some explanation:

#content {
    overflow: visible; /* default, but important to notice */
}

section {
    float: left;
    width: 25%;
}

h1 {
    position: fixed;
    width: 25%;
    background: #00FF00;
    text-align: center;
}

and the demo fiddle: http://jsfiddle.net/audetwebdesign/4zLMq/

How This Works

Your #content block takes up the remaining width to the right of your 200px left floated sidebar.

Within #content, you have two left-floated section elements that take up 25% of the parent container, which in this case, is the width of the view port panel.

Your child h1 elements have position: fixed, which means that their width of 25% is also computed based on the width of the viewport (not #content).

Case 1
If you want h1 and #content to have the same width, they need to have the same relative (25%) computed from the same containing block (view port in this case).

However, the value of 25% is not 25% of the remaining space after you account for the floated sidebar. However, maybe you can live with this.

Case 2
You could make the width values a bit easier to determine if you set the sidebar width to be a relative value. Using mixed units is always an issue.

like image 52
Marc Audet Avatar answered Oct 19 '22 00:10

Marc Audet