[html] How to center an element in the middle of the browser window?

How can I place some HTML element (say, a <div>, for example) in the middle of a browser window (not page, not screen)? Not depending on browser window size, screen resolution, toolbar layout, etc. E.g. I want it to be in the middle of the browser window.

This question is related to html css

The answer is


I don't think you can do that. You can be in the middle of the document, however you don't know the toolbar layout or the size of the browser controls. Thus you can center in the document, but not in the middle of the browser window.


Working solution.

<html>
          <head>
            <style type="text/css">
                html
                {
                    width: 100%;
                    height: 100%;
                }

                body
                {
                    display: flex;
                    justify-content: center;
                    align-items: center;
                }
            </style>
        </head>

        <body>
            Center aligned text.(horizontal and vertical side)
        </body>
</html>

To do this you need to know the size of the element you are centering. Any measurement will do (i.e. px, em, percent), but it has to have a fixed size.

The css will look as follows:

 // Replace X and Y with a number and u with a unit. do calculations
 // and remove parens
.centered_div {
   width: Xu;
   height: Yu;
   position: absolute;
   top: 50%;
   left: 50%;
   margin-left: -(X/2)u;
   margin-top: -(Y/2)u;
}

Edit: This centers in the viewport. You can only center in the browser window using JavaScript. But that might be good enough anyway, since you probably want to display a popup/modal box?


You could write a JavaScript wto find the window height and width and make it to half to find the centre point.

Add you stuff inside a tag, and set the div top and left from the javascript to the centre coordinates you have found using Javascript.

Let me know if you need the code.


you can center any object in viewport, here is an example using jquery

$(document).ready(function()
{


posicionar("#midiv");
$(window).on("resize", function() {
    posicionar("#midiv");   
});

function posicionar(elemento){
    var altoDocumento = $(window).height();//alto
    var anchoDocumento = $(window).width();
    //console.log(altoDocumento);
    //console.log(anchoDocumento);
    var centroXDocumento = anchoDocumento / 2;
    var centroYDocumento = altoDocumento / 2;
    //console.log(centroXDocumemnto,centroYDocumento);
    var altoElemento = $(elemento).outerHeight(true);//ancho real del elemento
    var anchoElemento = $(elemento).outerWidth(true);//alto 

    var centroXElemento = anchoElemento / 2;// centro x del elemento
    var centroYElemento = altoElemento / 2; // centro y del elemento

    var posicionXElemento = centroXDocumento - centroXElemento;
    var posicionYElemento = centroYDocumento - centroYElemento;

    $(elemento).css("position","absolute");
    $(elemento).css("top", posicionYElemento);
    $(elemento).css("left", posicionXElemento);
}
});

the html

<div id="midiv"></div>

Note: you must execute the function onDomReady and when the window resizes.

here is de jsfiddle http://jsfiddle.net/geomorillo/v82x6/


Hope this helps. Trick is to use absolute positioning and configure the top and left columns. Of course "dead center" will depend on the size of the object/div you are embedding, so you will need to do some work. For a login window I used the following - it also has some safety with max-width and max-height that may actually be of use to you in your example. Configure the values below to your requirement.

div#wrapper {
    border: 0;
    width: 65%;
    text-align: left;
    position: absolute;
    top:  20%;
    left: 18%;
    height: 50%;
    min-width: 600px;
    max-width: 800px;
}

div#wrapper {
    position: absolute;
    top:  50%;
    left: 50%;
    transform: translate(-50%,-50%);
}

This should work with any div or screen size:

_x000D_
_x000D_
.center-screen {_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
  justify-content: center;_x000D_
  align-items: center;_x000D_
  text-align: center;_x000D_
  min-height: 100vh;_x000D_
}
_x000D_
 <html>_x000D_
 <head>_x000D_
 </head>_x000D_
 <body>_x000D_
 <div class="center-screen">_x000D_
 I'm in the center_x000D_
 </div>_x000D_
 </body>_x000D_
 </html>
_x000D_
_x000D_
_x000D_

See more details about flex here. This should work on most of the browsers, see compatibility matrix here.


If you don't know the size of the browser you can simply center in CSS with the following code:

HTML code:

<div class="firstDiv">Some Text</div>  

CSS code:

 .firstDiv {
  width: 500px;

  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);

  background-color: #F1F1F1;
 }

This also helps in any unforeseen changes in the future.


<div align="center">

or

<div style="margin: 0 auto;">

I had a lot of problems with centring and alignment until I found Flexbox as a recommendation in a guide.

A Complete Guide to Flexbox

I'll post a snippet (that works with Chrome) here for convenience:

<head>
    <style type="text/css">
        html
        {
            width: 100%;
            height: 100%;
        }

        body
        {
            display: flex;
            justify-content: center;
            align-items: center;
        }
    </style>
</head>

<body>
    This is text!
</body>

For more details, please refer to the article.


This is checked and works in all browsers.

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

        <style type="text/css">
            html, body { margin: 0; padding: 0; height: 100%; }

            #outer {height: 100%; overflow: hidden; position: relative; width: 100%;}
            #outer[id] {display: table; position: static;}

            #middle {position: absolute; top: 50%; width: 100%; text-align: center;}
            #middle[id] {display: table-cell; vertical-align: middle; position: static;}

            #inner {position: relative; top: -50%; text-align: left;}
            #inner {margin-left: auto; margin-right: auto;}
            #inner {width: 300px; } /* this width should be the width of the box you want centered */
        </style>
    </head>
    <body>

        <div id="outer">
            <div id="middle">
                <div id="inner">
                    centered
                </div>
            </div>
        </div>

    </body>
</html>

This is completely possible with just CSS-- no JavaScript needed: Here's an example

Here is the source code behind that example:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>  
<meta http-equiv="content-type" content="text/html;charset=ISO-8859-1">
<title>Dead Centre</title>  
<style type="text/css" media="screen"><!--
body 
    {
    color: white;
    background-color: #003;
    margin: 0px
    }

#horizon        
    {
    color: white;
    background-color: transparent;
    text-align: center;
    position: absolute;
    top: 50%;
    left: 0px;
    width: 100%;
    height: 1px;
    overflow: visible;
    visibility: visible;
    display: block
    }

#content    
    {
    font-family: Verdana, Geneva, Arial, sans-serif;
    background-color: transparent;
    margin-left: -125px;
    position: absolute;
    top: -35px;
    left: 50%;
    width: 250px;
    height: 70px;
    visibility: visible
    }

.bodytext 
    {
    font-size: 14px
    }

.headline 
    {
    font-weight: bold;
    font-size: 24px
    }

#footer 
    {
    font-size: 11px;
    font-family: Verdana, Geneva, Arial, sans-serif;
    text-align: center;
    position: absolute;
    bottom: 0px;
    left: 0px;
    width: 100%;
    height: 20px;
    visibility: visible;
    display: block
    }

a:link, a:visited 
    {
    color: #06f;
    text-decoration: none
    }

a:hover 
    {
    color: red;
    text-decoration: none
    }

--></style>
</head>
<body>
<div id="horizon">
    <div id="content">
        <div class="bodytext">
        This text is<br>
        <span class="headline">DEAD CENTRE</span><br>
        and stays there!</div>
    </div>
</div>
<div id="footer">
    <a href="http://www.wpdfd.com/editorial/thebox/deadcentre4.html">view construction</a></div>
</body>
</html>

It works for me :).

div.parent {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
}

If I understand you correct, you want to center the element vertically and horizontally based on the window, not the document. It can be a bit of a pain, but you can use javascript to detect the window size, scroll position, element size, etc. and then position the element in the center of the window (not the document, but the viewable window).

If you want this element to remain in the moddule of the window as you scroll you would need to capture the scroll event and adjust the position.

The code for doing this differs from one browser to the next.


To centre align a div you should apply the style

div 
{
    margin: 0 auto;
}

Here is:

  • HTML+CSS only solution - no JavaScript needed
  • It does not require that you to know the content size in advance
  • The content stands centered on window resizing

And the example:

<!DOCTYPE html>
<html>
    <head>
        <title>HTML centering</title>

        <style type="text/css">
        <!--
        html, body, #tbl_wrap { height: 100%; width: 100%; padding: 0; margin: 0; }
        #td_wrap { vertical-align: middle; text-align: center; }
        -->
        </style>
    </head>

    <body>
        <table id="tbl_wrap"><tbody><tr><td id="td_wrap">
        <!-- START: Anything between these wrapper comment lines will be centered -->


<div style="border: 1px solid black; display: inline-block;">
This content will be centered.
</div>

        <!-- END: Anything between these wrapper comment lines will be centered -->
        </td></tr></tbody></table>
    </body>
</html>

Take a look at the original URL for full info: http://krustev.net/html_center_content.html

You can do whatever you like with this code. The only condition is that any derived work must have a reference to the original author.