Как разместить div в середине экрана, когда страница больше экрана - PullRequest
130 голосов
/ 16 февраля 2011

Привет, я использую что-то похожее на следующее, чтобы расположить div в середине экрана:

<style type="text/css"> 
#mydiv {
    position:absolute;
    top: 50%;
    left: 50%;
    width:30em;
    height:18em;
    margin-top: -9em; /*set to a negative number 1/2 of your height*/
    margin-left: -15em; /*set to a negative number 1/2 of your width*/
    border: 1px solid #ccc;
    background-color: #f3f3f3;
}

</style>


<div id="mydiv">Test Div</div>

Однако проблема в том, что он позиционирует элемент в середине страницы.не экран.Так что, если страница имеет несколько экранов в высоту, и я нахожусь в верхней части страницы (верхняя часть детали отображается на экране), когда я показываю элемент div, его даже нет на экране.Вы должны прокрутить вниз, чтобы просмотреть его.

Может кто-нибудь, пожалуйста, скажите мне, как бы вы отобразили его в середине экрана?

Ответы [ 14 ]

247 голосов
/ 16 февраля 2011

просто добавьте position:fixed, и оно останется в поле зрения даже при прокрутке вниз.посмотрите на http://jsfiddle.net/XEUbc/1/

#mydiv {
    position:fixed;
    top: 50%;
    left: 50%;
    width:30em;
    height:18em;
    margin-top: -9em; /*set to a negative number 1/2 of your height*/
    margin-left: -15em; /*set to a negative number 1/2 of your width*/
    border: 1px solid #ccc;
    background-color: #f3f3f3;
}
80 голосов
/ 01 августа 2013

Я думаю, что это простое решение:

<div style="
    display: inline-block;
    position: fixed;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    width: 200px;
    height: 100px;
    margin: auto;
    background-color: #f3f3f3;">Full Center ON Page
</div>
48 голосов
/ 08 марта 2016

Если вы знаете размер элемента, вы можете просто использовать свойство margin:

#mydiv {
  position: fixed;
  top: 50%;
  left: 50%;
  margin-top: -50px; //assuming that #mydiv has the height of 100px
  margin-left: -100px; //assuming that #mydiv has the width of 200px
}

Обратите внимание , что вы должны использовать половину ширины и высоты элемента

Но если вы не уверены в размере, это поможет:

#mydiv {
   position: fixed;
   top: 50%;
   left: 50%;
   transform: translate(-50%, -50%);
}
11 голосов
/ 27 ноября 2015

Использовать преобразование;

<style type="text/css">
    #mydiv {
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
    }
</style>

Решение Javascript:

var left = (screen.width / 2) - (530 / 2);
var top = (screen.height / 2) - (500 / 2);
var _url = 'PopupListRepair.aspx';
window.open(_url, self, "width=530px,height=500px,status=yes,resizable=no,toolbar=no,menubar=no,left=" + left + ",top=" + top + ",scrollbars=no");
5 голосов
/ 04 февраля 2014

Просто поставь margin:auto;

#mydiv {
    margin:auto;
    position:absolute;
    top: 50%;
    left: 50%;
    width:30em;
    height:18em;
    margin-top: -9em; /*set to a negative number 1/2 of your height*/
    margin-left: -15em; /*set to a negative number 1/2 of your width*/
    border: 1px solid #ccc;
    background-color: #f3f3f3;
}

<div id="mydiv">Test Div</div>
3 голосов
/ 20 марта 2016
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;

Это сработало для меня

2 голосов
/ 31 октября 2015

Краткий ответ, просто добавьте position:fixed, и это решит вашу проблему

1 голос
/ 21 июня 2017

Хорошо, ниже приведен рабочий пример для этого.

Это будет обрабатывать центральное положение, если вы измените размер веб-страницы или загрузите в anysize.

<!DOCTYPE html>
<html>
<head>
<style>
.loader {
  position: absolute;
  top: 50%;
  left: 50%;
  margin-top: -50px;
  margin-left: -50px;
  border: 10px solid #dcdcdc;
  border-radius: 50%;
  border-top: 10px solid #3498db;
  width: 30px;
  height: 30px;
  -webkit-animation: spin 2s linear infinite;
  animation: spin 1s linear infinite;  
}

@-webkit-keyframes spin {
  0% { -webkit-transform: rotate(0deg); }
  100% { -webkit-transform: rotate(360deg); }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>
</head>
<body>


<div class="loader" style="display:block"></div>

</body>
</html>

В приведенном выше примере загрузка div всегда будет в центре.

В надежде, что это будетпомочь вам:)

1 голос
/ 15 февраля 2017
<html>
<head>
    <style type="text/css">

#mydiv {
    position:absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    width:100px;
    height:200px;
    margin:auto;
    border: 1px solid #ccc;
    background-color: #f3f3f3;
}
    </style>
</head>
<body>
<div id="mydiv">Maitrey</div>
</body>
</html>
0 голосов
/ 21 июня 2018
width:30em;
position: static;
margin: 0px auto 0px auto;
padding: 0px;
...