[css] How to align a <div> to the middle (horizontally/width) of the page

I have a div tag with width set to 800 pixels. When the browser width is greater than 800 pixels, it shouldn't stretch the div, but it should bring it to the middle of the page.

This question is related to css html alignment center

The answer is


If your center content is deep inside other divs then only margin can save you. Nothing else. I face it always when not using a framework like Bootstrap.


This can be easily achieved via flex container.

.container{
 width: 100%;
 display: flex;
 height: 100vh;
 justify-content: center;
}

.item{
 align-self: center;
}

Preview Link


position: absolute and then top:50% and left:50% places the top edge at the vertical center of the screen, and the left edge at the horizontal center, then by adding margin-top to the negative of the height of the div, i.e., -100 shifts it above by 100 and similarly for margin-left. This gets the div exactly in the center of the page.

_x000D_
_x000D_
#outPopUp {_x000D_
  position: absolute;_x000D_
  width: 300px;_x000D_
  height: 200px;_x000D_
  z-index: 15;_x000D_
  top: 50%;_x000D_
  left: 50%;_x000D_
  margin: -100px 0 0 -150px;_x000D_
  background: red;_x000D_
}
_x000D_
<div id="outPopUp"></div>
_x000D_
_x000D_
_x000D_


In my case, the phone screen size is unknown, and here is what I did.

HTML

<div class="loadingImg"></div>

CSS

.loadingImg{
    position: fixed;
    top: 0px;
    left: 0px;
    z-index: 9999999;
    border: 0;
    background: url('../images/loading.gif') no-repeat center;
    background-size: 50px 50px;
    display: block;
    margin: 0 auto;
    -webkit-border-radius: 50px;
    border-radius: 50px;
}

JavaScript (before you need to show this DIV)

$(".loadingImg").css("height",$(document).height());
$(".loadingImg").css("width",$(document).width());
$(".loadingImg").show();

Use the below code for centering the div box:

_x000D_
_x000D_
.box-content{_x000D_
    margin: auto;_x000D_
    top: 0;_x000D_
    right: 0;_x000D_
    bottom: 0;_x000D_
    left: 0;_x000D_
    position: absolute;_x000D_
    width: 800px;_x000D_
    height: 100px;_x000D_
    background-color: green;_x000D_
}
_x000D_
<div class="box-content">_x000D_
</div>
_x000D_
_x000D_
_x000D_


Add this class to the div you want centered (which should have a set width):

.marginAutoLR
{
    margin-right:auto;
    margin-left:auto;
}

Or, add the margin stuff to your div class, like this:

.divClass
{
    width:300px;
    margin-right:auto;
    margin-left:auto;
}

Simply use the center tag just after the body tag, and end the center tag just before body ends:

<body>
    <center>
        ... Your code here ...
    </center>
</body>

This worked for me with all the browsers I have tried.


You can also use it like this:

<div style="width: 60%; margin: 0px auto;">
    Your contents here...
</div>

body, html {
    display: table;
    height: 100%;
    width: 100%;
}
.container {
    display: table-cell;
    vertical-align: middle;
}
.container .box {
    width: 100px;
    height: 100px;
    background: red;
    margin: 0 auto;
}

http://jsfiddle.net/NPV2E/

"width:100%" for the "body" tag is only for an example. In a real project you may remove this property.


Div centered vertically and horizontally inside the parent without fixing the content size

Here on this page is a nice overview with several solutions, too much code to share here, but it shows what is possible...

Personally I like this solution with the famous transform translate -50% trick the most. It works well for both fixed (% or px) and undefined height and width of your element.
The code is as simple as:

HTML:

<div class="center"><div>

CSS:

.center {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%); /* for IE 9 */
  -webkit-transform: translate(-50%, -50%); /* for Safari */

  /* optional size in px or %: */
  width: 100px;
  height: 100px;
}

Here a fiddle that shows that it works


  • Get the width of the screen.
  • Then make margin left 25%
  • Make margin right 25%

In this way the content of your container will sit in the middle.

Example: suppose that container width = 800px;

<div class='container' width='device-width' id='updatedContent'>
    <p id='myContent'></p>
    <contents></contents>
    <contents></contents>
</div>

if ($("#myContent").parent === $("updatedContent"))
{
    $("#myContent").css({
        'left': '-(device-width/0.25)px';
        'right': '-(device-width/0.225)px';
    });
}

<body>
    <div style=" display: table; margin: 250 auto;">
        In center
    </div>
</body>

If you want to change the vertical position, change the value of 250 and you can arrange the content as per your need. There is no need to give the width and other parameters.


_x000D_
_x000D_
parent {_x000D_
    position: relative;_x000D_
}_x000D_
child {_x000D_
    position: absolute;_x000D_
    left: 50%;_x000D_
    transform: translateX(-50%);_x000D_
}
_x000D_
<parent>_x000D_
  <child>_x000D_
  </child>_x000D_
</parent>
_x000D_
_x000D_
_x000D_


Flexbox solution is the way to go in/from 2015. justify-content: center is used for the parent element to align the content to the center of it.

HTML

<div class="container">
  <div class="center">Center</div>
</div>

CSS

.container {
  display: flex;
  justify-content: center;
}
.center {
  width: 800px;
}

Output

_x000D_
_x000D_
.container {
  display: flex;
  justify-content: center;
}
.center {
  width: 400px; 
  padding: 10px;
  background: #5F85DB;
  color: #fff;
  font-weight: bold;
  font-family: Tahoma;
}
_x000D_
<div class="container">
  <div class="center">Centered div with left aligned text.</div>
</div>
_x000D_
_x000D_
_x000D_


  1. Do you mean that you want to center it vertically or horizontally? You said you specified the height to 800 pixels, and wanted the div not to stretch when the width was greater than that...

  2. To center horizontally, you can use the margin: auto; attribute in CSS. Also, you'll have to make sure that the body and html elements don't have any margin or padding:

html, body { margin: 0; padding: 0; }
#centeredDiv { margin-right: auto; margin-left: auto; width: 800px; }

Simple http://jsfiddle.net/8pd4qx5r/

html {
  display: table;
  height: 100%;
  width: 100%;
}

body {
  display: table-cell;
  vertical-align: middle;
}

.content {
  margin: 0 auto;
  width: 260px;
  text-align: center;
  background: pink;
}

Use the CSS flex property: http://jsfiddle.net/cytr/j7SEa/6/show/

body {                       /* Centered */
  display: box;
  flex-align: center;
  flex-pack: center;
}

<div></div>
div {
  display: table;
  margin-right: auto;
  margin-left: auto;
}

For some reason, none of the previous answers worked for me really. This is what worked for me and it works across browsers as well:

.center {
    text-align: center;
    height: 100%;

    /* Safari, Opera, and Chrome */
    display: -webkit-box;
    -webkit-box-pack: center;
    -webkit-box-align: center;

    /* Firefox */
    display: -moz-box;
    -moz-box-pack: center;
    -moz-box-align: center;

    /* Internet Explorer 10 */
    display: -ms-flexbox;
    -ms-flex-pack: center;
    -ms-flex-align: center;
}

Some other pre-existing setups from older code that will prevent div page centering L&R are:

  1. Other classes hidden in external stylesheet links.
  2. Other classes embedded in something like an img (like for older external CSS print format controls).
  3. Legend code with IDs and/or CLASSES will conflict with a named div class.

To make it also work correctly in Internet Explorer 6 you have to do it as follows:

HTML

<body>
    <div class="centered">
        centered content
    </div>
</body>

CSS

body {
    margin: 0;
    padding: 0;
    text-align: center; /* !!! */
}

.centered {
    margin: 0 auto;
    text-align: left;
    width: 800px;
}

If you have some regular content, and not only one line of text, the only possible reason I know is to calculate margin.

Here is an example:

HTML

<div id="supercontainer">
  <div id="middlecontainer">
    <div class="common" id="first">first</div>
    <div id="container">
      <div class="common" id="second">second</div>
      <div class="common" id="third">third</div>
    </div>
  </div>
</div>

CSS

body {
  margin: 0;
  padding: 0;
}

.common {
  border: 1px solid black;
}

#supercontainer {
  width: 1200px;
  background: aqua;
  float: left;
}

#middlecontainer {
  float: left;
  width: 104px;
  margin: 0 549px;
}

#container {
  float: left;
}

#first {
  background: red;
  height: 102px;
  width: 50px;
  float: left;
}

#second {
  background: green;
  height: 50px;
  width: 50px;
}

#third {
  background: yellow;
  height: 50px;
  width: 50px;
}

So, #supercontainer is your "whole page" and its width is 1200px.

#middlecontainer is div with content of your site; it's width 102px. In case the width of content is known, you need to divide the page's size to 2, and subtract half of content's width from the result: 1200 / 2 - (102 / 2) = 549;

Yes, I'm also seeing that this is der grosse fail of CSS.


.middle {
   margin:0 auto;
   text-align: center;
}

/* it brings div to center */


This also works in Internet Explorer, but auto margins do not.

.centered {
    position: absolute;
    display:  inline-block;
    left:     -500px;
    width:    1000px;
    margin:   0 50%;
}

Use justify-content and align-items to horizontally and vertically align a div

https://developer.mozilla.org/de/docs/Web/CSS/justify-content https://developer.mozilla.org/en/docs/Web/CSS/align-items

_x000D_
_x000D_
html,_x000D_
body,_x000D_
.container {_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
}_x000D_
.container {_x000D_
  display: flex;_x000D_
  align-items: center;_x000D_
  justify-content: center;_x000D_
}_x000D_
.mydiv {_x000D_
  width: 80px;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="mydiv">h & v aligned</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_


Centering without specifying div width:

body {
  text-align: center;
}

body * {
  text-align: initial;
}

body div {
  display: inline-block;
}

This is something like <center> tag does, except:

  • all direct inline childs elements (eg. <h1>) of <center> will also positioned to center
  • inline-block element can have different size (comapred to display:block setting) according to browser defaults

Examples related to css

need to add a class to an element Using Lato fonts in my css (@font-face) Please help me convert this script to a simple image slider Why there is this "clear" class before footer? How to set width of mat-table column in angular? Center content vertically on Vuetify bootstrap 4 file input doesn't show the file name Bootstrap 4: responsive sidebar menu to top navbar Stylesheet not loaded because of MIME-type Force flex item to span full row width

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to alignment

How do I center text vertically and horizontally in Flutter? CSS align one item right with flexbox What's the difference between align-content and align-items? align images side by side in html How to align iframe always in the center How to make popup look at the centre of the screen? Responsive image align center bootstrap 3 How to align title at center of ActionBar in default theme(Theme.Holo.Light) Center align a column in twitter bootstrap How do I position an image at the bottom of div?

Examples related to center

Center Plot title in ggplot2 How to make a <div> or <a href="#"> to align center How to center an unordered list? Bootstrap 3 modal vertical position center How to align title at center of ActionBar in default theme(Theme.Holo.Light) How to center absolute div horizontally using CSS? Resize to fit image in div, and center horizontally and vertically Center fixed div with dynamic width (CSS) RelativeLayout center vertical Center button under form in bootstrap