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

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


<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 vertically center of the screen, and left edge at horizontally center, then by adding margin-top to negative of height of the div ie -100 shifts it above by 100, similarly for margin-left . This gets 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>  

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

  • 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; }
    
    链接地址: http://www.djcxy.com/p/7136.html

    上一篇: 如何使浏览器窗口的高度达到100%?

    下一篇: 如何将<div>与页面的中间(水平/宽度)对齐