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

HtmlCss

Html Problem Overview


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.

Html Solutions


Solution 1 - 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?

Solution 2 - Html

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

Solution 3 - Html

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.

Solution 4 - Html

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

Solution 5 - 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>

Solution 6 - Html

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.

Solution 7 - Html

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.

Solution 8 - Html

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.

Solution 9 - Html

<div align="center">

or

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

Solution 10 - Html

To centre align a div you should apply the style

div 
{
    margin: 0 auto;
}

Solution 11 - Html

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>

Solution 12 - Html

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.

Solution 13 - Html

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.

Solution 14 - Html

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.

Solution 15 - Html

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

Solution 16 - Html

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>

Solution 17 - Html

It works for me :).

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

Solution 18 - Html

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/

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKamareyView Question on Stackoverflow
Solution 1 - HtmlPatrikAkerstrandView Answer on Stackoverflow
Solution 2 - HtmlSammanView Answer on Stackoverflow
Solution 3 - HtmlCanerView Answer on Stackoverflow
Solution 4 - HtmlKamareyView Answer on Stackoverflow
Solution 5 - HtmlCugaView Answer on Stackoverflow
Solution 6 - HtmlDelian KrustevView Answer on Stackoverflow
Solution 7 - HtmlAnand MohantyView Answer on Stackoverflow
Solution 8 - HtmlAhmed ElsawalhyView Answer on Stackoverflow
Solution 9 - HtmlthreadhackView Answer on Stackoverflow
Solution 10 - HtmlgonzohunterView Answer on Stackoverflow
Solution 11 - HtmlMichal MView Answer on Stackoverflow
Solution 12 - HtmlPim JagerView Answer on Stackoverflow
Solution 13 - HtmlJames ConigliaroView Answer on Stackoverflow
Solution 14 - HtmlBhaskarView Answer on Stackoverflow
Solution 15 - HtmlRyan OberoiView Answer on Stackoverflow
Solution 16 - HtmlVinayakView Answer on Stackoverflow
Solution 17 - HtmlKiry MeasView Answer on Stackoverflow
Solution 18 - HtmlGeomorilloView Answer on Stackoverflow