Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 690
Shimmy Weitzhandler Avatar asked Jun 05 '09 01:06

Shimmy Weitzhandler


People also ask

How do I fix a div in the middle of my screen?

You basically need to set top and left to 50% to center the left-top corner of the div. You also need to set the margin-top and margin-left to the negative half of the div's height and width to shift the center towards the middle of the div.

How do you position an element in the middle of a page?

Like last time, you must know the width and height of the element you want to center. Set the position property of the parent element to relative . Then set the child's position property to absolute , top to 50% , and left to 50% . This just centers the top left corner of the child element vertically and horizontally.


2 Answers

<body>     <div style="width:800px; margin:0 auto;">         centered content     </div> </body> 
like image 151
AgileJon Avatar answered Oct 03 '22 13:10

AgileJon


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>
like image 28
Summo Avatar answered Oct 03 '22 12:10

Summo