[GIS] How to center Openlayers div on screen

openlayers-2

I have a div centered on screen (using width:75%;height:50%;margin: 0 auto;)
When I init the map div with OL , it auto aligned to the left.
How can I keep having the div in the center of the window?

Best Answer

Your div containing map must be positioned absolutely. If you know the required height and width of your map, it could be as follows:

  #map{
    position: absolute!important;
    top: 50%;
    left: 50%;
    width: 400px;
    height: 300px;
    margin-top: -150px!important; /*negative half of height*/
    margin-left: -200px!important; /*negative half of width*/
  }

Note the !important rule. It will override the default css properties set by OpenLayers. In case you are not sure about absolute height and width of your map div, you can use .width() and .height(). Calculate scrren width and height, and set css properties of map div from javascript.