Friend of Kim
Friend of Kim

Reputation: 860

How to center a fixed div inside another div?

I have one main div that should make the page scrollable. On either side of this div there is a sidebar. The only difference I want from how it is now, is that the sidebars should always stay on top (position: fixed;)

I've tried everything, but it doesn't work. If I put position: fixed; on the .fixed, the width is no longer 100 % but the width of the actual contents inside. If I put on width: 100% the width turns 100 % of the viewport.

Is this even possible with just CSS?

JSFiddle: http://jsfiddle.net/6yWNv/

Sidebar 1
<div id="wrapper">
    <div class="contents">
        <p>Lorem ipsum dolor sit amnet.</p>
    </div>
</div>
<div class="sidebar">
    <div class="contents">
        <div class="fixed">
            Sidebar 2
        </div>
    </div>
</div>

html, body {margin: 0; padding: 0;}

#wrapper {
    width: 54%;
    float: left;
    background: #0FF;
}

.sidebar {
    width: 23%;
    float: left;
}
.sidebar .contents {
    margin: auto;
    background: #F00;
    min-width: 100px;
    width: 55%;
    height: 100px;
}

.sidebar .contents .fixed {
    background: #0F0;
}

Upvotes: 0

Views: 909

Answers (3)

thebjorn
thebjorn

Reputation: 27311

The trick is to set position:fixed on the sidebar (with left:0 and right:0 respectively) and then add margin-left:23% to #wrapper:

#wrapper {
    width: 54%;
    margin-left: 23%;
    background: #0FF;
}

.sidebar {
    width: 23%;
    position: fixed;
    left:0; top: 0;
}

#wrapper + .sidebar {  /* target second sidebar */
    left: inherit;     /* reset left */
    right:0;
}

if you want the green sidebars to stay in place, but the red boxes to move away, then something like this should work:

.sidebar {
    width: 23%;
    float: left;
    position: relative;   /* so sub-containers are relative to sidebar */
}
.sidebar .contents {
    margin: auto;
    background: #F00;
    min-width: 100px;
    width: 100%;          /* relative to sidebar */
    height: 100px;
}

.sidebar .contents .fixed {
    background: #0F0;
    position: fixed;      /*  starts a new context... */
    width: 23%;           /*  so this is not relative to sidebar *.
}

Upvotes: 3

John Kurlak
John Kurlak

Reputation: 6680

Not possible with just CSS. When you make an element fixed, it removes it from its "context" and makes its new "context" the document. That's why specifying width: 100% on the position: fixed element spans the page.

Edit: I'm assuming that you want the green sidebars to stay in place but the red boxes to move away as you scroll (I'm making this assumption because of the way you've named your classes on your page).

Upvotes: 2

PA.
PA.

Reputation: 29339

you need to fix the sidebar, not its contents.

Just remove the float and set the position fixed to top and right

  .sidebar {
        width: 30%;
        position: fixed;
        top:0;
        right:0;
    }

Upvotes: 1

Related Questions