Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to center an element in the middle of the browser window?

Tags:

html

css

How can I place some HTML element (say, a <div>, for example) in the middle of a browser window (not page, not screen)? Not depending on browser window size, screen resolution, toolbar layout, etc. E.g. I want it to be in the middle of the browser window.

like image 800
Kamarey Avatar asked Jun 11 '09 16:06

Kamarey


People also ask

How do you place an element in the middle of the page?

To horizontally center a block element (like <div>), use margin: auto; Setting the width of the element will prevent it from stretching out to the edges of its container.

How do I center content in my browser?

Set the following style to that div: width: 1000px; margin: auto; This should center your content.

How do I center my browser window?

Press Alt + Space . Press M (for “Move”). Use the arrow keys to move the window exactly where you want it.

How do you center a form in the middle of the screen?

Use the CSS text-align Property to Center a Form in HTML The text-align property takes the values like left , right , center , justify , etc. We can set the value to center to center the form. For example, apply the text-align property to the form tag in the style attribute, and set the property to center .


2 Answers

To do this you need to know the size of the element you are centering. Any measurement will do (i.e. px, em, percent), but it has to have a fixed size.

The css will look as follows:

 // Replace X and Y with a number and u with a unit. do calculations  // and remove parens .centered_div {    width: Xu;    height: Yu;    position: absolute;    top: 50%;    left: 50%;    margin-left: -(X/2)u;    margin-top: -(Y/2)u; } 

Edit: This centers in the viewport. You can only center in the browser window using JavaScript. But that might be good enough anyway, since you probably want to display a popup/modal box?

like image 142
PatrikAkerstrand Avatar answered Sep 21 '22 06:09

PatrikAkerstrand


div#wrapper {     position: absolute;     top:  50%;     left: 50%;     transform: translate(-50%,-50%); } 
like image 28
Samman Avatar answered Sep 22 '22 06:09

Samman