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

<body>
    <div style="width:800px; margin:0 auto;">
        centered content
    </div>
</body>

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.

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

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

Output

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

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