user3241664
user3241664

Reputation: 13

How to center a div with a specific width and fixed positioning?

I am coding, and trying to center my div horizontally in the middle of the page. It's just a plain div, with nothing inside of it right now. My code is this:

#wrapper{
width:500px;
height:100%;
position:fixed;
background-color:#fff;
}

Basically, I just want a 500px width white rectangle centered in the page horizontally, that takes up 100% of the page's height.

Thanks.

Upvotes: 1

Views: 107

Answers (2)

user934902
user934902

Reputation: 1204

You need to use left 50% and add a margin of negative half the width

#wrapper{
width:500px;
height:100%;
left: 50%;
margin-left: -250px;
position:fixed;
background-color:#fff;
}

If you are using this div as a container for a webpage I would recommend taking out position fixed and using margin: 0 auto; to center the div

Upvotes: 2

Alessandro Minoccheri
Alessandro Minoccheri

Reputation: 35973

you can assign left:50% and after margin-left (width-of-div / 2), in this way you can center div in fixed/absolute position

try this:

#wrapper{
   width:500px;
   height:100%;
   position:fixed;
   background-color:#fff;
   left:50%;
   margin-left:-250px;
}

DEMO

Upvotes: 3

Related Questions