83

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.

1
  • 1
    What do you mean by window? As in the exact centre, including address bars, tab bar, status bar, menu bar, etc? If so, then I don't think it's possible without doing something like writing a plugin that can do some lookups of pixel sizes in the browser.
    – workmad3
    Jun 11, 2009 at 16:16

18 Answers 18

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

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?

1
  • It centered great on my browser! Here is the html: <!doctype html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <title>Center Page</title> <style type="text/css"> #centered_div { width: 60px; height: 20px; position: absolute; top: 50%; left: 50%; margin-left: -30px; margin-top: -10px; } </style> </head> <body> <div id="centered_div"> Centered </div> </body> </html>
    – Craigo
    Oct 6, 2011 at 23:19
27

This should work with any div or screen size:

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

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

1
  • 1
    Solved my issue with centering bootstrap3 modal-dialog with image inside! Good and simple and direct approach.
    – Honza P.
    May 21, 2021 at 13:25
20

I surprised that nobody said about position=fixed. It makes exactly what I asked and works in all "human" browsers and IE since 7.

0
14

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>
3
  • 1
    But it still is dead-center relative to the document. Not to the browser-window.
    – Pim Jager
    Jun 11, 2009 at 16:26
  • 1
    It looks middle of the browser-window to me... no matter what you do (resize, etc) in IE or FF, it's still smack-dab in the middle...
    – Cuga
    Jun 11, 2009 at 16:34
  • @Cuga but there is no scrollable content.
    – tundoopani
    Dec 20, 2011 at 21:58
10

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.

0
10

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.

1
  • I tried it on IE 11, mozilla firefox and chrome. Was perfectly centered. Apr 14, 2015 at 20:13
6

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.

5
<div align="center">

or

<div style="margin: 0 auto;">
1
  • 1
    That only centers horizontally.
    – brettkelly
    Jun 11, 2009 at 16:18
2

To centre align a div you should apply the style

div 
{
    margin: 0 auto;
}
1

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>
1
  • if body's height isn't 100%, but say 3000px, you will see that text is in at a middle of a document, e.g. you should scroll down to see it.
    – Kamarey
    Jun 11, 2009 at 16:40
0

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.

2
  • This isn't true. This example even works for browser resizes: wpdfd.com/editorial/thebox/deadcentre3.html
    – Cuga
    Jun 11, 2009 at 16:26
  • Yes, but still relative to the document (which resizes as the browser window is resizes). However when you open this in Firefox and Chrome ans you maximize them both. You will see that the text is on a different place becease Chrome's document is bigger, even though the browser windows are the same size.
    – Pim Jager
    Jun 11, 2009 at 16:33
0

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.

1
  • I tried to solve this by javascript, but was unable to get viewable window coords. I don't think it's possible to calculate them, even for one of browsers.
    – Kamarey
    Jun 11, 2009 at 16:29
0

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.

0

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;
}
0

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>
0

It works for me :).

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

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/

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.