Results 1 to 9 of 9
Thread: [CSS] centering on the screen
-
April 15th, 2008, 06:38 PM #1
[CSS] centering on the screen
if I have a DIV that's 400px by 200px, how do I center it on the screen? When I try to do the following, it only centers the top left corner on the screen. I want the exact center of the DIV to be centered.
PHP Code:#box {
width: 400px;
height: 200px;
position: absolute;
top: 50%;
left: 50%;
}

-
April 15th, 2008, 07:00 PM #2Code:
#box { width: 400px; height: 200px; margin: 0 auto; }
*edit:
Err.. that will horizontally center it....
Come to think of it I dont think i've ever made something that required it to be vertically centered in the browser..... so i am unfamiliar how to do it :/
-
April 15th, 2008, 09:50 PM #3
I don't think it's possible to center something vertically. Without the use of Javascript of course. Even then it is a big pain with all the browsers.... Wish everyone would just use Firefox. That'd make my life.
-
April 15th, 2008, 10:51 PM #4
http://www.wpdfd.com/editorial/thebox/deadcentre4.html
for fixed height and fixed width. It use to be used a lot of flash sites before people started just making them 100%x100%
-
April 15th, 2008, 11:05 PM #5
Nice one temp
-
April 16th, 2008, 12:59 AM #6
So the solution is (in psuedo programming):
PHP Code:int w = 500;
int h = 200;
#box {
width: w;
height: h;
position: absolute;
left: 50%;
top: 50%;
margin: -h/2 0 0 -w/2;
}

-
April 16th, 2008, 10:25 AM #7
If you want the div centered just horizontally then use either..
or if you don't want to use absolute positioning..Code:#box { height: h; left: 50%; margin: -(half height)px 0 0 -(half width)px; position: absolute; width: w; }
That's the easiest way to do it horizontally. However, if you want it vertically also, then the link Templarian posted is the way to go.Code:#box { height: h; margin: 0 auto; width: w; }
Quick explanation of the link to get it vertically centered:
You are going to need to nest your #box inside of another div that is positioned at "top: 50%" and then add negative margin-top to your #box (half the height to be exact).
Hope that helps a little if there was anything fuzzy!
Last edited by redelite; April 16th, 2008 at 10:26 AM. Reason: dumb CSS mistake 0_o
-
April 16th, 2008, 10:37 AM #8
Why would you need the box within another div? My solution works (at least on FF and IE7).

-
April 16th, 2008, 10:49 AM #9
Because if you just do "top: 50%", you aren't centering the box vertically, you are only saying *start the box 50% from the top of the page*.
Edit: Woops.. I for some reason didn't realize there was negative margin-top
.. Sorry about that
Last edited by redelite; April 16th, 2008 at 11:10 AM.

Reply With Quote



Bookmarks