Question

I'm struggling to centrally align a div within a div with position:fixed (I need it fixed as this UI will float over the rest of an existing page). The central div will contain a considerable amount of content so needs to scroll vertically. It also needs to scale horizontally with respect to the viewport with a maxwidth.

Here's what I have so far - it is almost there - just can't work out how to centralise the yellow div.

http://jsfiddle.net/p7F3u/

EDIT I need to support IE9, FF, Chrome, Safari if possible

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title>Test</title>
    <style>
        div {
            padding: 0px;
            margin: 0px;
        }
        #fix {
            position: fixed;
            left: 0px;
            right: 0px;
            top: 0px;
            bottom: 0px;
            background-color: red;
        }
        #my-wrap {
            position: relative;
            margin: 1em auto;
            background-color: green;
            width: 100%;
            height: 100%;
        }
        #my-details {
            position: absolute;
            width: 50%;
            max-width: 450px;
            top: 20px;
            background-color: yellow;
            bottom: 0px;
            overflow: scroll;
        }
    </style>
</head>
<body>
    <div id="fix">
        <div id="my-wrap">
            <div id="my-details">
                <p>Lots of content in here....</p>
                <br style="clear: both" />
            </div>
        </div>
    </div>
</body>
</html>

Thanks!

Was it helpful?

Solution

The easiest approach would be to relatively position the #my-details element as opposed to absolutely positioning it. You could then simply use margin:0 auto to center the element. Since the element is no longer absolutely positioned, you need to give it a height of 100%. To displace top:20px, you could simply use calc() like so: height: calc(100% - 20px).

Exmaple Here

#my-details {
    position:relative;
    margin:0 auto;
    height:calc(100% - 20px);
    width: 50%;
    max-width: 450px;
    top: 20px;
    background-color: yellow;
    bottom: 0px;
    overflow: scroll;
}

As an alternative, you could change top:20px to a percentage based value such as 2%. You could then simply use a height of 98% and avoid having to use calc(). Since that may not be an optimal solution, you could also use the following:

Example Here

#fix {
    padding-top:1em;
}
#my-wrap {
    padding-top:20px;
}

Basically, this method avoids top:20px by adding a padding-top value on the parent element instead. The parent of that element then receives a padding-top value of 1em to displace the margin: 1em auto.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top