How to keep a div in the center of the page?

I use jQuery to create a β€œdialog” that should appear on top of the page and in the center of the page (vertically and horizontally). How do I make it stay in the center of the page (even if the user is resizing or scrolling?)

+3
source share
5 answers

I would use

position: fixed;
top: 50%;
left: 50%;
margin-left: -(dialogwidth/2);
margin-top: -(dialogheight/2);

but with this solution and the browser viewport size is smaller than your dialog box, portions of the dialog will not be accessible from the top and left because they are outside the viewport. Therefore, you need to decide if the size of the dialogs is right for you.

(CSS , , , , .)

Edit:

, IE6, - :

#dialog { position: absolute; }
#dialog[id] { position: fixed; }

IE6 , IE6 , ​​ . ( . . .)

+8

- Infinity.

#mydiv {
   background-color:#F3F3F3;
   border:1px solid #CCCCCC;
   height:18em;
   left:50%;
   margin-left:-15em;
   margin-top:-9em;
   position:absolute;
   top:50%;
   width:30em;
}

CSS, , .

, , - . , , 50% .

+3

div , : 0 auto. , IE div, text-align: center, div .

0

(width/height + padding), CSS:

elementContainerSelector {
    position: fixed; /* You'll of course need to handle browsers that don't support fixed positioning */
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

elementSelector {
    position: absolute;
    top: 50%;
    left: 50%;
    margin: -[half of offset height]px 0 0 -[half of offset width]px;
}

Hurix .

0

margin-left: auto margin-right: auto

0

Source: https://habr.com/ru/post/1713901/


All Articles