How to align a <div> to the middle (horizontally/width) of the page
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>
<body>
<div style="width:800px; margin:0 auto;">
centered content
</div>
</body>
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>