tags:

views:

1661

answers:

4

I am looking to vertically center a <div> in the viewport (browser window) without resorting to Javascript (pure HTML and CSS only). I have several constraints:

  • The div must be centered vertically in the viewport. Methods I have seen only support centering inside another <div>, which is not what I want.
  • The height of the div is not known.

Other constraints:

  • The div must be aligned to the right.
  • The div has a constant width.
  • The div must support padding.
  • Other elements will be placed on the web page. The div acts as a menu.
  • The div must support a background colour/image.

This gets me close to what I want, but not exactly:

#nav {
    position: fixed;
    right: 0;
    top: 50%;
}

However, the top of the nav is in the middle, not the middle of the nav.

Is there some technique which allows me to center my div with these constraints?

A: 

Here's a good tutorial explaining how to do it, and why to do it that way.

This tutorial also explains how, but focuses on centering a div.

Ben S
Neither of the two methods in your link meet my constraints.
strager
+1  A: 

This article might help:

http://www.jakpsatweb.cz/css/css-vertical-center-solution.html

I've used it before it seems to work in Safari/Firefox.

Steve Willard
Perfect. Thanks!
strager
+1  A: 

The easiest way is not to use a div - use a table with one row and one cell. Vertical alignment is woefully unsupported in CSS and you will find yourself coding up the wall and across the ceiling to accomplish it.

I understand the semantic argument against what I have just proposed - I am a proponent of semantic markup in most cases. However I also believe in using the right tool for the right job. I believe it is best to sacrifice a little purity in this case for a simple solution that will work.

Andrew Hare
Amen. Had to be said.
Paolo Bergantino
Read my first constraint, please. How would this solve that problem?
strager
Tables are nothing special. In Standards Mode, setting height on a table has exactly the same effect as setting height on a div. Only Quirks Mode sizes table height relative to the viewport by default; you can get this behaviour in Standards Mode by setting ‘height: 100%’ on every ancestor element.
bobince
+1  A: 

Have a look at Dead Centre. You were heading in the right direction already.

Darko Z