theeggman85
theeggman85

Reputation: 1825

Centering divs and giving them top/bottom positioning?

I want to center a div, but at the same time be able to use something like top: 100px; in my code. Is this possible? I notice that if I say position: fixed; then the top/bottom styles will work, but margin-left: auto and margin-right: auto are disabled. How can I get both features at once? Thanks!

Upvotes: 3

Views: 281

Answers (3)

brains911
brains911

Reputation: 1310

http://jsfiddle.net/nb6zY/2/

Setting the margins of a fixed element will work, just not with 'auto'. I use the following technique often when creating modals:

div {
  width:100px;
  position:fixed; 
  top:100px;
  left:50%; 
  margin-left:-50px;
}

This only works if you know the width of the div you want to center. The trick is setting margin-left to a negative 'half' of the div width.

Upvotes: 2

No Results Found
No Results Found

Reputation: 102745

Depending on what you're using this for, the easiest way might be to use two elements: an "invisible" one with fixed position and an inner element which is centered. Something like this:

http://jsfiddle.net/CCqUn/

<div>
    <p>Test</p>
</div>
div {
    position:fixed;
    top:100px;
    width:100%;
    height:0; /* In case of z-index issues; this element should be "hidden" */
}
div p {
    width:200px;   
    margin:0 auto;
    background:#CCC;
}

Upvotes: 4

Chris Kempen
Chris Kempen

Reputation: 9661

I would be tempted to use a containing element (99% of the time a div), together with margins / padding, rather than top coordinates (which tend to be more for exact positioning relative to other elements whose position and size are known). Check out the following:

<div class="container">
    <div class="content">
        Some content in here..!
    </div>
</div>

...then the CSS:

.container
{
    width: 100%;
}

.content
{
    width: 200px;
    background-color: ORANGE;

    /* set it to the center of the container, plus move it down */
    /* using 100px for the top margin */
    margin: 100px auto 0px;
}

This would set the left and right margins to auto, leave the bottom margin 0px, and make the top margin 100px.

Obviously, for center-positioning of elements, the 0px auto margin setting would be the best, but if you know the exact coordinates at which you'd like the element to be positioned, relative to the container, you can try the following too (CSS):

.container
{
    width: 100%;
    position: relative;
}

.content
{
    width: 200px;
    background-color: ORANGE;

    /* exact coordinates, relative to the container (parent) */
    position: absolute;
    top: 100px;
    left: 100px;
}

Hope this helps!

Upvotes: 1

Related Questions